In bash, if you have an array arr
and you want to print all its values, the command
echo ${arr[@]}
will do the trick. In sh
however, this command gives a bad substitution
error. What is an alternative command(s) for this task in sh?
In bash, if you have an array arr
and you want to print all its values, the command
echo ${arr[@]}
will do the trick. In sh
however, this command gives a bad substitution
error. What is an alternative command(s) for this task in sh?
There is no such thing as a general-purpose array in the POSIX sh specification. The closest thing you have available for an arbitrary variable is a string separated by some delimiter; usually whitespace separated, but can be separated by other characters if the elements themselves can contain spaces.
$@
can be treated as an array in POSIX sh, but it's a bit limited due to the fact that there's only one such variable. You can change the value of $@
with set
, so you can do the following:
$ set -- one "two three" four
$ echo "$#"
3
$ echo "$1"
one
$ echo "$2"
two three
$ echo "$3"
four
$ printf '"%s" "%s" "%s"\n' "$@"
"one" "two three" "four"
Couple questions:
- Can you provide any further details on the script and how the array is being initialized?
- Are you sure that you're actually using sh? On some system /bin/sh is a symlink something else like bash.
ls -l /bin/sh
lrwxrwxrwx 1 root root 4 2013-06-04 19:52 /bin/sh -> bash
I would recommend http://www.tutorialspoint.com/unix/unix-using-arrays.htm as a starting point.