簡體   English   中英

Bash循環命令通過包含空格的列表

[英]Bash loop command through list containing spaces

我有一個腳本,其中包含使用同一列表的多個循環命令。 看起來像這樣:

# 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

我嘗試使用反斜杠轉義,引用它和其他多種方式,但是我無法使其正常工作。

您應該在讀取時將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

為什么應該使用列表而不是直接從目錄獲取應用程序文件名? 如果將來要添加新應用,則必須更新腳本。

也許這是從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM