我需要一个脚本来获取Mac上/ Volumes目录中的所有目录并将它们存储在一个数组中。我遇到的问题是,在目录名中有一个空格是很常见的,这真的让人感到困惑。 这是我到目前为止所得到的:
LOCATION="/Volumes"
COUNTER=0
cd $LOCATION
OIFS=$IFS
IFS=$'\n'
for folder in *; do
[ -d "$folder" ] || continue
(( DRIVES[$COUNTER] = ${folder} ))
(( COUNTER = COUNTER + 1 ))
done
IFS=$OIFS
以下是我收到的错误:
./getDrives.sh: line 17: DRIVES[0] = Macintosh HD : syntax error in expression (error token is "HD ")
答案 0 :(得分:1)
我想最简单的只是:
array=( /Volumes/*/ )
注意:
nullglob
或failglob
设置.
也不是..
),请设置dotglob
如果您想要所有目录和子目录(递归),请设置globstar
并使用
array=( /Volumes/**/ )
代替。
当我说设置nullglob
或failglob
或dotglob
或globstar
时,我的意思是shell选项,可以设置,例如:
shopt -s nullglob
并且未设置,例如:
shopt -u nullglob
The Shopt Builtin section of the Bash Reference Manual中有关这些内容的更多信息。
回答你的评论:你只需要目录的基名,而不是完整的路径?很容易,只是做
cd /Volumes
array=( */ )
这就是全部。事实上,我建议你用一条效率更高的行替换6行低效代码。
更一般地说,如果您不想cd
进入/Volumes
,您就可以轻松摆脱领先的/Volumes/
array=( /Volumes/*/ )
array=( "${array[@]/#\/Volumes\//}" )
或者,更好的是,将前导/Volumes/
放在变量中并继续:
location="/Volumes/"
array=( "$location"* )
array=( "${array[@]/#"$location"/}" )
答案 1 :(得分:0)
cd /Volumes
cnt=0
for d in *; do
[ -d "$d" ] || continue
drv[$cnt]="$d"
((++cnt))
done
for d in "${drv[@]}"; do
echo "$d"
done