Docs > Bash Handbook > Shell-expansions
Shell expansions
Expansions are performed on the command line after it has been split into tokens. In other words, these expansions are a mechanism to calculate arithmetical operations, to save results of commands' executions and so on.
If you are interested, you can read more about shell expansions.
Brace expansion
Brace expansion allows us to generate arbitrary strings. It's similar to filename expansion. For example:
echo beg{i,a,u}n # begin began begun
Also brace expansions may be used for creating ranges, which are iterated over in loops.
echo {0..5} # 0 1 2 3 4 5
echo {00..8..2} # 00 02 04 06 08
Note: the rule here is {00..8..2} represents {start..end..steps}
echo {0..10..3} # 0 3 6 9
Command substitution
Command substitution allow us to evaluate a command and substitute its value into another command or variable assignment. Command substitution is performed when a command is enclosed by ``
or $()
. For example, we can use it as follows:
now=`date +%T`
# or
now=$(date +%T)
echo $now # 19:08:26
Arithmetic expansion
In bash we are free to do any arithmetical operations. But the expression must enclosed by $(( ))
The format for arithmetic expansions is:
result=$(( ((10 + 5*3) - 7) / 2 ))
echo $result # 9
Within arithmetic expansions, variables should generally be used without a $
prefix:
x=4
y=7
echo $(( x + y )) # 11
echo $(( ++x + y++ )) # 12
echo $(( x + y )) # 13
Double and single quotes
There is an important difference between double and single quotes. Inside double quotes variables or command substitutions are expanded. Inside single quotes they are not. For example:
echo "Your home: $HOME" # Your home: /Users/<username>
echo 'Your home: $HOME' # Your home: $HOME
Take care to expand local variables and environment variables within quotes if they could contain whitespace. As an innocuous example, consider using echo
to print some user input:
INPUT="A string with strange whitespace."
echo $INPUT # A string with strange whitespace.
echo "$INPUT" # A string with strange whitespace.
The first echo
is invoked with 5 separate arguments — $INPUT is split into separate words, echo
prints a single space character between each. In the second case, echo
is invoked with a single argument (the entire $INPUT value, including whitespace).
Now consider a more serious example:
FILE="Favorite Things.txt"
cat $FILE # attempts to print 2 files: `Favorite` and `Things.txt`
cat "$FILE" # prints 1 file: `Favorite Things.txt`
While the issue in this example could be resolved by renaming FILE to Favorite-Things.txt
, consider input coming from an environment variable, a positional parameter, or the output of another command (find
, cat
, etc). If the input might contain whitespace, take care to wrap the expansion in quotes.