Bash循环命令通过包含空格的列表

时间:2016-03-23 08:43:53

标签: bash loops

我有一个使用相同列表的多个循环命令的脚本。它看起来像这样:

# 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

除了列表中的第四个应用程序之外,这似乎工作正常,因为应用程序名称中有一个空格。如果我在调试模式下运行脚本,这是输出:

+ 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

我尝试使用反斜杠进行转义,引用它以及其他多种方法,但我无法使其工作。

2 个答案:

答案 0 :(得分:1)

您应该在阅读时将IFS设置为\n并使用BASH数组而不是一个简单的变量来保存由换行符分隔的所有条目:

#!/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

mapfile -t Applications <<'EndOfList'
/Applications/App.app
/Applications/App2.app
/Applications/App3.app
/Applications/Another App.app
EndOfList

答案 1 :(得分:0)

为什么你应该使用列表来直接从目录中获取应用程序文件名? 如果您将来要添加新应用,则必须更新脚本。

也许这可能是从dir获取文件的想法: 我创建了一个目录Applications,并触及了脚本中的第4个文件:

#!/bin/bash

# List of applications


for file in Applications/*.app
do
        echo "file[$file]"
    if [ -e "$file" ]; then
        echo ""$file" found"
    fi;
done

exit 1

输出

[shell] ➤ ./tttttt
file[Applications/Another App.app]
Applications/Another App.app found
file[Applications/App.app]
Applications/App.app found
file[Applications/App2.app]
Applications/App2.app found
file[Applications/App3.app]
Applications/App3.app found