从for循环中的数组创建目录

时间:2013-04-17 20:23:16

标签: linux arrays bash scripting redhat

我有一系列客户名称,我想用它来制作目录。下面是我正在运行的代码:

$ echo "$customerArray=( customer1 customer2 customer3 customer4 customer5 )"

for customerName in $( customerArray ); 
do
    mkdir -p /home/$customerName
    mkdir -p /home/$customerName/outbound
    mkdir -p /home/$customerName/outbound_backup
    mkdir -p /home/$customerName/dropoff
done

任何人都可以向我解释我做错了吗?

2 个答案:

答案 0 :(得分:4)

你不能在字符串文字中设置变量,我很确定$( customerArray )也是无效的。请尝试以下方法:

customerArray=(customer1 customer2 customer3 customer4 customer5)
for customerName in ${customerArray[@]}
do
    ...
done

您需要将数组变量引用为${customerArray[@]}${customerArray[*]}bash manual更深入地描述了这一点。

答案 1 :(得分:2)

这将是一个可行的替代方案 brace expansion

customerArray=(customer1 customer2 customer3 customer4 customer5)
for customerName in ${customerArray[*]}
do
  mkdir -p /home/$customerName/{outbound,outbound_backup,dropoff}
done