-------------------------------------- Command Substitution - $(unix command) -------------------------------------- -Ian! D. Allen - idallen@idallen.ca Unix shell Command Substitution is similar to variable substitution in that some text is being interpolated into the shell command line before a command is run. Variable substitution looks like this: $ x='hello there' $ echo "and I said $x to her" and I said hello there to her In Unix shell Command Substitution, it is the standard output of a Unix command line that is substituted. The command line is executed and all the standard output is captured and becomes the result of the substitution in the command line before it is executed by the shell: $ echo "the date is $(date) today" the date is Sat Jan 29 04:19:14 EST 2005 today $ echo "the passwd file has $(wc -l echo "the date is:" > date > echo "today" > ) $ echo "$foo" the date is: Sat Jan 29 05:47:51 EST 2005 today Command substitution looks like variable substitution and it is done at the same time as variable substitution by the shell. In particular, this means that the output of a command substitution is subject to blank-splitting and GLOB expansion if the command substitution is not itself double-quoted and protected from the shell: $ touch a b c '*' # create a file name of asterisk * $ ls # ls output is by rows onto a terminal * a b c $ ls | cat # ls output is one column into a pipe or file * a b c $ echo "the files are $(ls)" # double-quoted command substitution the files are * # quoted ls output is one column a b c $ echo the files are $(ls) # WRONG! expansion is missing double quotes! the files are * a b c a b c # first * is GLOB expanded by shell! In the last example above, the output of the unquoted $(ls) command substitution expansion contains a GLOB character (the '*' file name) that the shell then GLOB-expands before it calls the echo command. Remember to double-quote your variables (including command substitutions)!