2013-05-13 31 views
0

我在bash腳本中很新,不知道爲什麼這段代碼不起作用(是的,我一直在搜索)。Bash數組和循環不會一起工作

這裏是我的代碼:

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' 

任何想法?

在此先感謝。

+0

「不起作用」是什麼意思?你預期會發生什麼,實際發生了什麼? – 2013-05-13 01:56:31

+0

@AdamLiss終端說有一個「語法錯誤附近的意外標記fi'」... – Aslet 2013-05-13 02:00:22

+0

'printf'%s%s \ n'「$ {commands [i]}」「$ {descriptions [i]}」 ''可以用'echo'$ {commands [i]} $ {descriptions [i]}''替換 - - 更乾淨更好。 – Bill 2013-05-13 02:09:38

回答

1

您不能在單引號內使用單引號。做到這一點,它將"'"視爲一個單引號字符串並連接它們。

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

並使用${#commands[@]}來獲取數組長度。

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

現在它說「-bash:PROMPT_COMMAND:第2行:語法錯誤:意外的文件結尾」 但是的,我不能相信我忘了「那麼」 – Aslet 2013-05-13 02:05:14

+0

你應該把所有的變量放在引號中。 – Bill 2013-05-13 02:07:04

+0

@Bill你是什麼意思?他們不是已經? – Aslet 2013-05-13 02:09:20