BASH
10
array demo sh
Guest on 13th May 2022 01:38:52 AM
#!/bin/bash
#
# Usage:
# ./array-demo.sh
set -o nounset
set -o pipefail
set -o errexit
args() {
python -c 'import sys; print sys.argv[1:]' "$@"
}
show-b() {
args "${b[@]}"
}
array-demo() {
a=('Track 01.mp3' 'Track 02.mp3')
# Here are 4 incorrect ways to pass an array to a command, and one correct
# way, using 8 chars.
echo RESULTS OF BAD WAYS TO PASS AN ARRAY
echo
args ${a} # only gives the first item
args ${a[*]}
args "${a[*]}"
args ${a[@]}
echo
echo -n 'GOOD WAY is "${a[@]}" -> '
args "${a[@]}" # Using it correctly takes 8 chars
echo
echo RESULTS OF BAD WAYS TO COPY AN ARRAY
echo
# Here are 8 incorrect ways to copy an array, and 1 correct way, using 10
# extra characters besides the name of the array.
b=$a
show-b # only gives the first item
b=${a[*]}
show-b
b="${a[*]}"
show-b
b=${a[@]}
show-b
b="${a[@]}" # Doesn't work!
show-b
b=( $a )
show-b
b=( ${a[*]} )
show-b
b=( "${a[*]}" )
show-b
b=( ${a[@]} )
show-b
b=( "${a[@]}" ) # Copying it correctly takes 10 chars. You need to
# SPLICE the old array into a new array.
echo
echo -n 'GOOD WAY is b=( "${a[@}}" ) -> '
show-b
echo
}
array-demo "$@"