Matt Parkins
Matt Parkins

Reputation: 24688

In Bash scripting, how is (*) interpreted?

Given the following partial bash script, how is the first line being interpreted?

Is this a shortcut to the bash command ls?

l=(*)
for v in ${l[@]}
do 
    echo $v  
done

Output:

arc
cgi-bin
dist

Interestingly, if I type "*" into a bash shell I get the error "bash: arc: command not found", presumably this is related somehow?

Upvotes: 1

Views: 396

Answers (2)

Michael Jaros
Michael Jaros

Reputation: 4681

Try typing echo *, that will make things more clear.

By the way, you could have also written:

for v in *
do 
    echo "$v"
done

Upvotes: 1

tripleee
tripleee

Reputation: 189417

No; the parentheses just declare an array in this context. The shell is what expands the * glob.

In some more detail,

variable=(value1 value2)

declares an array with two elements; and the glob * expands to the names of all (non-hidden) files in the current directory. If you have files or directories named arc, cgi-bin, and dist, and type

*

you are attempting to run the command

arc cgi-bin dist

which of course fails if you don't have a cormand named arc anywhere in your PATH.

As an aside, ${l[@]} is incorrect; you definitely want "${l[@]}" with double quotes - otherwise you are losing the integrity of any quoted strings in the array (just like $@ is basically always an error, and needs to be "$@"). To just print the array, you don't need a loop;

printf '%s\n' "${l[@]}"

Upvotes: 7

Related Questions