--- layout: page category-page: scripts category-title: Scripting tags: parameter expansion brace variable check condition author: Marco Tereh title: Parameter expansion --- There are some special operations that can be performed on variables and strings called parameter expansions. The general syntax for all parameter expansions is this one:
${CODE_HERE}Depending on what you want to do with your variable, the code that goes inside the braces differs.
${VARIABLE:-DEFAULT_VALUE}If the variable VARIABLE exists and has a value (i.e. it is not null), this is equal to the value of VARIABLE. Otherwise, it is equal to DEFAULT_VALUE.
echo "First name: ${firstname:-John}";
${VARIABLE:=DEFAULT_VALUE}If the variable VARIABLE exists and has a value, this is equal to the value of VARIABLE. Otherwise, it sets the variable to DEFAULT_VALUE and is equal to it.
echo "Last name: ${lastname:=Doe}";
${VARIABLE:?ERR_VALUE}If the variable VARIABLE exists and has a value, this is equal to the value of VARIABLE. Otherwise, it prints ERR_VALUE to STDERR and exits (meaning nothing else will be executed after this).
currdate=${date:?Operation failed: date unknown};
${VARIABLE:+VALUE}If the variable VARIABLE exists and has a value, this is equal to VALUE. Otherwise, this has no effect.
echo -e "reading from address $read.${write:+\nWARNING: read and write set at the same time}";
${VARIABLE: NUMBER}This is equal to the substring of the value of VARIABLE, starting at the character with (0-based) index NUMBER
lastname=${fullname:$firstnamelength};
${VARIABLE: FROM:LENGTH}This is equal to the substring of the value of VARIABLE, starting at the character with (0-based) index FROM with length LENGTH
lastname=${middlename:$firstnamelength:$middlenamelength};
${#VARIABLE}This is equal to the length of the value of VARIABLE
echo "your name has ${#name} characters";