Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `dash` support `bash` style arrays?

In the dash shell environment I am looking to split a string into arrays. The following code works in bash but not in dash.

IFS=""
var="this is a test|second test|the quick brown fox jumped over the lazy dog"
IFS="|"
test=( $var )
echo ${test[0]}
echo ${test[1]}
echo ${test[2]}

My Question

Does dash support arrays in this style. If not are there any suggestions for parsing this out into an another type of variable without the use of a loop?

like image 596
Blackninja543 Avatar asked Jan 29 '13 23:01

Blackninja543


People also ask

Does Bash support array?

Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.

Are strings arrays in Bash?

In this example, all the elements are numbers, but it need not be the case—arrays in Bash can contain both numbers and strings, e.g., myArray=(1 2 "three" 4 "five") is a valid expression. And just as with any other Bash variable, make sure to leave no spaces around the equal sign.

What is array in Bash script?

Arrays are important concepts in programming or scripting. Arrays allow us to store and retrieve elements in a list form which can be used for certain tasks. In bash, we also have arrays that help us in creating scripts in the command line for storing data in a list format.


1 Answers

dash does not support arrays. You could try something like this:

var="this is a test|second test|the quick brown fox jumped over the lazy dog"
oldIFS=$IFS
IFS="|"
set -- $var
echo "$1"
echo "$2"
echo "$3"      # Note: if more than $9 you need curly braces e.g. "${10}"
IFS=$oldIFS

Note: Since the variable expansion $var is unquoted it gets split into fields according to IFS, which was set to a vertical bar. These fields become the parameters of the set command and as a result $1 $2 etc contain the sought after values.

-- (end of options) is used so that no result of the variable expansion can be interpreted as an option to the set command.

like image 83
Scrutinizer Avatar answered Oct 02 '22 05:10

Scrutinizer