Bash循环命令通过包含空格的列表 [英] Bash loop command through list containing spaces
问题描述
我有一个脚本,其中包含使用同一列表的多个循环命令.看起来像这样:
I have a script with multiple loop commands using the same list. It looks like this:
# List of applications
read -r -d '' Applications << EndOfList
/Applications/App.app
/Applications/App2.app
/Applications/App3.app
/Applications/Another App.app
EndOfList
for file in $Applications
do
if [ -e "$file" ]; then
echo ""$file" found"
fi;
done
exit 1
除了列表中的第四个应用程序外,这似乎可以正常工作,因为应用程序名称中有一个空格.如果我在调试模式下运行脚本,则输出为:
This seems to work fine except for the fourth application in the list, because there's a space in the application name. If I run the script in debug mode, this is the output:
+ read -r -d '' Applications
+ for file in '$Applications'
+ '[' -e /Applications/App.app ']'
+ for file in '$Applications'
+ '[' -e /Applications/App2.app ']'
+ for file in '$Applications'
+ '[' -e /Applications/App3.app ']'
+ for file in '$Applications'
+ '[' -e /Applications/Another ']'
+ for file in '$Applications'
+ '[' -e App.app ']'
+ exit 1
我尝试用反斜杠转义,引用它和其他多种方式,但是我无法使其正常工作.
I've tried escaping with a backslash, quoting it and multiple other ways but I could not get it to work.
推荐答案
在读取和使用BASH数组而不是一个简单的变量来保存时,应将 IFS
设置为 \ n
所有以换行符分隔的条目:
You should set IFS
as \n
while reading and use BASH array rather a simple variable to hold all the entries delimited by newlines:
#!/bin/bash
IFS=$'\n' read -r -d '' -a Applications <<'EndOfList'
/Applications/App.app
/Applications/App2.app
/Applications/App3.app
/Applications/Another App.app
EndOfList
for file in "${Applications[@]}"
do
if [[ -e "$file" ]]; then
echo "$file found"
fi;
done
PS::如果您具有BASH 4+版本,请使用 mapfile
:
PS: If you have BASH 4+ version then use mapfile
:
mapfile -t Applications <<'EndOfList'
/Applications/App.app
/Applications/App2.app
/Applications/App3.app
/Applications/Another App.app
EndOfList
这篇关于Bash循环命令通过包含空格的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!