Parsing Output with a Function Call
Problem
You want to parse the output of some program into various variables to be used else-where 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.
Solution
Use a function call to parse the words:
#!/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
CRDAY=$7
CRTIME=$8
FILE=$9
}
lsparts $(ls -l "$1")
echo $FILE has $LCOUNT 'link(s)' and is $SIZE bytes long.Here’s what it looks like when it runs:
$ ./fnsize fnsize fnsize has 1 link(s) and is 311 bytes long. $
Discussion
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)' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access