0

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.

5
  • What does "doesn't work" mean? What did you expect to happen, and what actually happened? Commented May 13, 2013 at 1:56
  • @AdamLiss The terminal says there's a "syntax error near unexpected token `fi' "... Commented May 13, 2013 at 2:00
  • printf '%s %s\n' "${commands[i]}" "${descriptions[i]}" can be replaced using echo "${commands[i]} ${descriptions[i]}" -- much cleaner and better. Commented May 13, 2013 at 2:09
  • @Bill The thing is I need the two arrays to be printed side by side. Do you know how to do that? Commented May 13, 2013 at 2:16
  • 1
    What you have looks correct to me, given both arrays are of equal length. I recommend to use echo instead of printf. Pls see cyberciti.biz/faq/finding-bash-shell-array-length-elements Commented May 13, 2013 at 2:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Now it says "-bash: PROMPT_COMMAND: line 2: syntax error: unexpected end of file" But yeah I can't believe I forgot the "then"
You should put all variables in quotes.
it is good to use elif [ "$usertype" = hacker ] instead of elif [ $usertype = hacker ]
also hacker should be "hacker" and same for normal

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.