Command substitution is a feature that allows output to be expanded from a command. It can be used to assign the output of a command to a variable, or to imbed the output of a command within another command. The format for command substitution is: $(command) where command is executed and the output is substituted for the entire $(command) construct. For example, to print the current date in a friendly format: $ echo The date is $(date) The date is Fri Jul 27 10:41:21 PST 1996 or see who is logged on: $ echo $(who q) are logged on now root anatole are logged on now Any commands can be used inside $(...), including pipes, I/O operators, metacharacters (wildcards), and more. We can find out how many users are logged on by using the who and wc l commands: $ echo $(who | wc l) users are logged on There are 3 users logged on Bourne Shell Compatibility For compatibility with the Bourne shell, the following format for command substitution can also be used: `command` Using `. . .` command substitution, we could get the names of the files in the current directory like this: $ echo `ls` are in this directory NEWS asp bin pc are this directory If you wanted a count of the files, a pipe to wc could be added: $ echo There are `ls | wc l` files here There are 4 files here Directing File Input There is also a special form of the $(...) command that is used to substitute the contents of a file. The format for file input substitution is: $(<file) This is equivalent to $(cat file) or `cat file`, except that it is faster, because an extra process does not have to be created to execute the cat command. A good use for this is assigning file contents to variables: $ cat foo a b c $ X=$(<foo) $ echo $X a b c We will talk about this later in Chapter 3. Arithmetic Operations Another form of the $(...) command is used to substitute the output of arithmetic expressions. The value of an arithmetic expression is returned when enclosed in double parentheses and preceded with a dollar sign. $((arithmetic-expression)) Here are a few examples. $ echo $((3+5)) 8 $ echo $((8192*16384%23)) 9 Performing arithmetic is discussed in detail in Chapter 6. |