Hielke Walinga
Hielke Walinga

Reputation: 2845

Declaration of an array valid for zsh and bash

I am looking for a way to declare an array that will work in bash and zsh.

I know I can do simply this in bash:

file_list=$(example_command)

And in zsh I can make it work like this:

file_list=($(example_command))

I know I can just do it with an if statement if I want to, but hope to do it without:

if [ `basename $SHELL`=bash ]; then
    file_list=$(example_command)
elif [ `basename $SHELL`=zsh ]; then 
    file_list=($(example_command))
else
    echo "ERROR: UNKNOWN SHELL"
fi

I do not really care about other shells (eg sh). Just looking for something working in zsh and bash which is not too exotic looking.

Upvotes: 1

Views: 1348

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295490

Your assumptions about bash are wrong. file_list=$(example_command) does not create an array there. file_list=( $(example_command) ) does create an array in both shells, though it's not good practice to do so (can't deal with files with spaces, files whose names could be expanded as a glob, etc).

The following is a good-practice approach (insofar as you can call handling filenames in a newline-delimited stream good-practice when newlines can be literals in filenames) that works in both shells:

file_list=( )
while IFS= read -r line; do file_list+=( "$line" ); done < <(example_command)

Importantly, to use an array in a way that works in both shells, you need to expand it as "${file_list[@]}", not $file_list.

Upvotes: 2

Related Questions