我有一個像這樣建構的變數:
ATTSTR=""
for file in $LOCALDIR/*.pdf
do
ATTSTR="${ATTSTR} -a \"${file}\""
done
該變數現在包含(注意檔案名稱中的空格):
ATTSTR=' -a "/tmp/Testpage - PDFCreator.pdf"'
現在我想在像這樣的命令中使用這個變數:
mutt -s "Subject" "${ATTSTR}" [email protected]
但事實證明它像這樣擴展,因此命令失敗(注意擴展變數周圍添加的單引號):
mutt -s "Subject" ' -a "/tmp/Testpage - PDFCreator.pdf"' [email protected]
我希望我的變數在沒有單引號的情況下擴展,使用"$ATTSTR"
or$ATTSTR
更糟。我怎樣才能做到這一點?
答案1
眾所周知,檔案名稱在擴展字串中是不可靠的;抵抗這種誘惑。
相反,使用大批保持檔案名稱完整,無論是否有空格:
arr=()
for f in $somedir/*.pdf
do
arr+=( -a "$f")
done
# and for usage/display:
mutt -s mysubject "${a[@]}" some@body
請參閱Bash 數組指南以供參考。
答案2
使用評估函數
command="mutt -s \"Subject\" $ATTSTR [email protected]"
response=$(eval "$command")