Busybox sh won't execute the bash script

Nayab Basha Sayed picture Nayab Basha Sayed · Jun 13, 2018 · Viewed 11.1k times · Source

I have a small script called test.sh which prints the value based on the index given.

#!/bin/sh
days_in_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
echo "${days_in_month[$1]}"

The above code works fine if I execute using bash.

$ bash test.sh 1
31

But I need to execute the same script in an embedded board which has sh as part of Busybox package. When I run the command in that board, it throws an error.

$ sh test.sh
test.sh: line 2: syntax error: unexpected "("

I observe that the same error is thrown when I use dash instead of bash in Ubuntu system.

$ dash test.sh
test.sh: line 2: syntax error: unexpected "("

Is there any way that I could change the code so that Busybox sh will execute without any errors?

Answer

Socowi picture Socowi · Jun 13, 2018

Both busybox' sh (which isash) and dash do not support arrays.

You could either write a big if-else or switch case statement, or use the following trick. We simulate an array using a single string with spaces as delimiters.

cut -d ' ' -f "$1" <<< "31 28 31 30 31 30 31 31 30 31 30 31"

or even more portable:

echo "31 28 31 30 31 30 31 31 30 31 30 31" | cut -d ' ' -f "$1"

Another workaround is to abuse the script's positional parameters as seen in this answer.