Aslet
Aslet

Reputation: 137

Bash array and loop won't work together

I am pretty new in bash script and can't figure out why this piece of code doesn't work (yes I've googled around).

Here's my code:

if [ $usertype = normal ]
then
    commands[0]="hi" ; descriptions[0]="get greeted"
    commands[1]="test" ; descriptions[1] = "test"
elif [ $usertype = hacker ]
    commands[0]="hi" ; descriptions[0]="get greeted"
    commands[1]="test" ; descriptions[1] = "test"
fi

alias fhelp='
for ((i=0; i<=${commands[@]}; i++))
do
    printf '%s %s\n' "${commands[i]}" "${descriptions[i]}"
done'

Any ideas?

Thanks in advance.

Upvotes: 0

Views: 118

Answers (2)

Yang
Yang

Reputation: 8170

You can't use single quotes inside single quotes. Do this, it treats "'" as a string of a single quote and concatenate them.

alias fhelp='
for ((i=0; i<=${commands[@]}; i++))
do
  printf '"'"'%s %s\n'"'"' "${commands[i]}" "${descriptions[i]}"
done'

And use ${#commands[@]} to get the array length.

Upvotes: 1

Zombo
Zombo

Reputation: 1

elif [ $usertype = hacker ]
# missing then!
commands[0]="hi" ; descriptions[0]="get greeted"

Upvotes: 1

Related Questions