bash脚本数组

时间:2012-05-01 23:48:21

标签: bash

array=('org.battery.plist' 'org.disk.plist' 'org.memory.plist');

echo "1) org.battery.plist"
echo "2) org.disk.plist"
echo "3) org.memory.plist"

echo "Enter selection(s) to load, separated by commas: "
read var

sudo launchctl load -w ${array[$var]}

我是否在正确的轨道上?我有点卡住了。有人可以帮忙吗?

如果用户输入1,2,我希望脚本在下面执行此操作 -

sudo launchctl load -w org.disk.plist
sudo launchctl load -w org.memory.plist

3 个答案:

答案 0 :(得分:1)

试试这个,

IFS=","
for i in $var
do
    sudo launchctl load -w ${array[$i - 1]}
done

您还需要检查输入是否超出数组范围,抛出和错误。

答案 1 :(得分:1)

bash中有一个建筑用于这样的选择,令人惊讶的是,称为“选择”:

select entry in ${array[@]}; 
do  
    sudo launchctl load -w $entry
done 

试试help select

答案 2 :(得分:0)

这样更好:

array=('org.battery.plist' 'org.disk.plist' 'org.memory.plist');

for (( i=0;i<"${#array[@]}";i++ )) ; do
    let n=i+1
    printf '%d) %s\n' $n "${array[$i]}"
done

IFS=, read -r -p 'Enter selection(s) to load, separated by commas: ' -a selections

for selection in "${selections[@]}" ; do
    let selection=selection-1
    sudo launchctl load -w "${array[$selection]}"
done