Shell Tricks

Printer-friendly version

Coding in sh or bash can be challenging. Here are some tricks I've learned over the years

Extracting fields from lists

I have a list of items in $LIST; each item is separated from each other item by a comma, and individual items may contain spaces.

~ $ LIST="abc,def ghi,jkl"
~ $ echo [$LIST]
[abc,def ghi,jkl]

I want an array, with one element per item in my list. I can't just

~ $ ARRAY=($LIST)

because the shell will break the list into items, not at the commas, but at the spaces, giving

~ $ echo There are ${#ARRAY[@]} elements in ARRAY
There are 2 elements in ARRAY
~ $ for element in "${ARRAY[@]}" ;
> do
> echo ARRAY element contains [$element]
> done
ARRAY element contains [abc,def]
ARRAY element contains [ghi,jkl]
~ $

To break the list at the comma, we have to do something special, we have to (temporarily) set IFS to a comma, before we load our ARRAY.

~ IFS=, ARRAY=($LIST)
~ echo There are ${#ARRAY[@]} elements in ARRAY
There are 3 elements in ARRAY
~ $ for element in "${ARRAY[@]}" ;
> do
> echo ARRAY element contains [$element]
> done
ARRAY element contains [abc]
ARRAY element contains [def ghi]
ARRAY element contains [jkl]
~

Articles: 
System Management: