6

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?

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
Blackninja543
  • 3,639
  • 5
  • 23
  • 32

1 Answers1

19

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.

Scrutinizer
  • 9,608
  • 1
  • 21
  • 22
  • You may want to use `set -f` to disable globbing. See note from shellcheck here: https://www.shellcheck.net/wiki/SC2086#exceptions – user12638282 Jun 06 '23 at 19:03