简体   繁体   English

在bash中循环遍历数组

[英]Looping through an Array in bash

I am currently attempting to create a bash script that will check inside of each users /Library/Mail folder to see if a folder named V2 exists. 我当前正在尝试创建一个bash脚本,该脚本将检查每个用户的/ Library / Mail文件夹内部,以查看是否存在名为V2的文件夹。 The script should create an array with each item in the array being a user and then iterate through each of these users checking their home folder for the above captioned contents. 该脚本应创建一个数组,并让该数组中的每个项目成为一个用户,然后遍历这些用户中的每一个,检查其主文件夹中是否包含上述字幕内容。 This is what I have so far: 这是我到目前为止的内容:

#!/bin/bash

cd /Users

array=($(ls))

for i in ${array[@]}
do

if [ -d /$i/Library/Mail/V2 ]

then
    echo "$i mail has been upgraded."
else 
    echo "$i FAIL"

fi

done

Populating your array from the output of ls is going to make for serious problems when you have a username with spaces. 当您的用户名带有空格时,从ls输出ls数组将导致严重的问题。 Use a glob expression instead. 请改用全局表达式。 Also, using [ -d $i/... ] will similarly break on names with spaces -- either use [[ -d $i/... ]] (the [[ ]] construct has its own syntax rules and doesn't require quoting) or [ -d "$i/..." ] (with the quotes). 同样,使用[ -d $i/... ]将类似地破坏带有空格的名称-要么使用[[ -d $i/... ]] (( [[ ]]结构具有自己的语法规则,不需要引号)或[ -d "$i/..." ] (带引号)。

Similarly, you need to double-quote "${array[@]}" to avoid string-splitting from splitting names with spaces in two, as follows: 同样,您需要对"${array[@]}"加双引号,以避免字符串拆分将名称用空格一分为二,如下所示:

cd /Users
array=(*)
for i in "${array[@]}"; do
  if [[ -d $i/Library/Mail/V2 ]]; then
    echo "$i mail has been upgraded."
  else 
    echo "$i FAIL"
  fi
done

That said, you don't really need an array here at all: 也就是说,您实际上根本不需要数组:

for i in *; do
  ...check for $i/Library/Mail/V2...
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM