BASH Array Cheatsheet

Windix Feng
2 min readJul 20, 2019

--

I was working on a BASH script to extract information from AWS cli result which requires capture multi-lines string and handling that in array.

For the script itself as an example, you can find it here.

Capture previous command’s output and convert it to array

There are many ways of doing this.

In my case, previous command generates results in multiple lines and I know there is no space in each line, I may capture that using () directly:

ARRAY=( $(command) )

The safer way (to handle spaces, glob chars like *, ?, [...]properly:

If you are using BASH v4 and above (not built-in on macOS at moment :( )

mapfile -t ARRAY < <( command )

Otherwise:

while IFS= read -r line; do
TASKS+=( "$line" )
done < <( command )

Check array length

if [[ ${#ARRAY[@]} -ne 1 ]]; then
echo "multiple entries found."
exit 1
fi

Print array properly

Use printf:

echo "ARRAY:"
printf '%s\n' "${ARRAY[@]}"

Use array as input for another command

Assume the other command requires space separated array elements:

command ${ARRAY[@]}

If only use a specific element referring by index:

command ${ARRAY[0]}

Check CLI argument (require at least one argument)

if [[ -z $1 ]]; then
echo "USAGE: $0 arguement"
exit 1
fi

Also notice the difference between $@ and $*

See this example:

In Dockerfile:

...
ENTRYPOINT ["./start.sh"]
CMD ['yarn', 'start']

In start.sh:

...
bash -c "$*"

Above are the working combination.

If we change to bash -c "$@" it actually runs yarn instead of yarn start as expected.

But bash -c "$@" would work with CMD ['yarn start'].

References

--

--

No responses yet