2015-04-23 23 views
1

我刚开始学习bash/shell以获得乐趣,我正在尝试创建一个应该接受用户输入的简单脚本,该脚本应该是预构建数组的名称,然后say该数组中的每个项目之间都有一个暂停。指定数组名称的用户输入[bash]

这是我到目前为止有:

#!/bin/sh 
array=("foo" "bar" "baz") 

read -p "Which array should I read to you? " answer 

for item in ${answer[@]} 
do 
    say "$item [[slnc 1000]]" 
done 

请让我知道你是否能在正确的方向指向我!

+1

http://mywiki.wooledge.org/BashFAQ/006 –

+0

我试过了,它正在工作(mac env)。 暂停包括 – AdrieanKhisbe

+0

您是否将其另存为文件?你用什么扩展名?你是怎么运行的?任何细节都会有帮助。此外,如果将空格添加到任何数组值中会发生什么情况 - 它仍然可以工作吗? –

回答

1

可以使用一个变量数组名这样的访问数组:

#!/bin/bash 

array=("foo" "bar" "baz") 
read -p "Which array should I read to you? " answer 

tmp="$answer"[@]; 

for item in "${!tmp}"; do 
    echo "$item [[slnc 1000]]" 
done 

然后用上面的脚本为:

bash arr.sh 
Which array should I read to you? array 
foo [[slnc 1000]] 
bar [[slnc 1000]] 
baz [[slnc 1000]] 
+0

非常感谢anubhava,我感觉有一个过渡的步骤,我在某处失踪,现在我学到了一些新东西! –

+1

不客气,很高兴帮助。 – anubhava