< Day Day Up > |
9.11. Command SubstitutionA string or variable can be assigned the output of a UNIX command by placing the command in backquotes. This is called command substitution. (On the keyboard, the backquote is normally below the tilde character.) If the output of a command is assigned to a variable, it is stored as a wordlist (see "Arrays" on page 447), not a string, so that each of the words in the list can be accessed separately. To access a word from the list, a subscript is appended to the variable name. Subscripts start at 1. Example 9.60.1 % echo The name of my machine is `uname -n`. The name of my machine is stardust. 2 % echo The present working directory is `pwd`. The present working directory is /home/stardust/john. 3 % set d = `date` % echo $d Sat Jun 20 14:24:21 PDT 2004 4 % echo $d[2] $d[6] Jun 2004 5 % set d = "'`date`" % echo $d[1] Sat Jun 20 14:24:21 PDT 2004 EXPLANATION
9.11.1 Wordlists and Command SubstitutionWhen a command is enclosed in backquotes and assigned to a variable, the resulting value is an array (wordlist). Each element of the array can be accessed by appending a subscript to the array name. The subscripts start at 1. If a subscript that is greater than the number of words in the array is used, the C shell prints Subscript out of range. If the output of a command consists of more than one line, the newlines are stripped from each line and replaced with a single space. Example 9.61.1 % set d = `date` % echo $d Fri Aug 27 14:04:49 PDT 2004 2 % echo $d[1–3] Fri Aug 27 3 % echo $d[6] 2004 4 % echo $d[7] Subscript out of range. 5 % echo "The calendar for the month of November is `cal 11 2004`" The calendar for month of November is November 2004 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 EXPLANATION
Example 9.62.1 % set machine = `rusers | awk '/tom/{print $1}'` 2 % echo $machine dumbo bambi dolphin 3 % echo $#machine 3 4 % echo $machine[$#machine] dolphin 5 % echo $machine dumbo bambi dolphin 6 % shift $machine % echo $machine bambi dolphin 7 % echo $machine[1] bambi 8 % echo $#machine 2 EXPLANATION
|
< Day Day Up > |