You want to parse the output of some program into various variables to be used elsewhere in your program.
Arrays are great when you are looping through the values, but not very readable if you want to refer to each separately, rather than by an index.
Use a function call to parse the words:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#!/usr/bin/env bash # cookbook filename: parseViaFunc # # parse ls -l via function call # an example of output from ls -l follows: # -rw-r--r-- 1 albing users 126 2006-10-10 22:50 fnsize function lsparts ( ) { PERMS=$1 LCOUNT=$2 OWNER=$3 GROUP=$4 SIZE=$5 CRDATE=$6 CRTIME=$7 FILE=$8 } lsparts $(ls -l "$1") echo $FILE has $LCOUNT 'link(s)' and is $SIZE bytes long. |
Here’s what it looks like when it runs:
1 2 3 |
$ ./fnsize fnsize fnsize has 1 link(s) and is 311 bytes long. $ |
We can let bash do the work of parsing by putting the text to be parsed on a function call.
Calling a function is much like calling a shell script. bash parses the words into separate variables and assigns them to $1, $2, etc.
Our function can just assign each positional parameter to a separate variable.
If the variables are not declared locally then they are available outside as well as inside the function.
We put quotes around the reference to $1 in the ls command in case the filename supplied has spaces in its name.
The quotes keep it all together so that ls sees it as a single filename and not as a series of separate filenames.
We use quotes in the expression ‘link(s)’ to avoid special treatment of the parentheses by bash.
Alternatively, we could have put the entire phrase (except for the echo itself) inside of double quotes—double, not single, quotes so that the variable substitution (for $FILE, etc.) still occurs.