[英]Passing quoted string arguments to a bash script
我在這里或其他任何地方都找不到解決這個看似簡單的問題的方法。 我想獲取嵌套目錄中所有文件的路徑,在它們周圍添加引號,然后在bash腳本中循環遍歷它們。 目錄名稱和文件中可以包含空格。 到目前為止,我沒有嘗試過任何正常的工作。 帶引號的路徑字符串總是在空格處分解。
test.sh
for var in "$@"
do
echo "$var"
done
我嘗試從每行一個路徑(單引號和雙引號)讀取文件:
find "nested directory with spaces" -type f | sed -e 's/^/"/g' -e 's/$/"/g' | tr '\n' '\n' > list.txt # double quotes
./test.sh `cat list.txt`
find "nested directory with spaces" -type f | sed -e 's/^/'\''/g' -e 's/$/'\''/g' | tr '\n' ' ' > list.txt # single quotes
./test.sh `cat list.txt`
並用引號路徑,單引號和雙引號之間的空格替換命令:
./test.sh `find "nested directory with spaces" -type f | sed -e 's/^/"/g' -e 's/$/"/g' | tr '\n' ' '` # double quotes
./test.sh `find "nested directory with spaces" -type f | sed -e 's/^/'\''/g' -e 's/$/'\''/g' | tr '\n' ' '` # single quotes
只需從命令行回顯帶引號的路徑即可獲得所需的結果。 可以將參數解析為完整字符串的腳本中缺少什么?
改為這樣做:
find "nested directory with spaces" -type f -exec ./test.sh {} +
這將使用多個參數調用test.sh
,而不會拆分文件名中的空格。
如果您的find
版本不支持+
,則可以使用\\;
相反,但這將為每個參數調用一次./test.sh
。
例如,給定腳本:
#!/bin/sh
echo start
for i; do
echo file: "$i"
done
+
和\\;
之間的區別 :
$ find a\ b.txt date.txt -exec ./test.sh {} +
start
file: a b.txt
file: date.txt
$ find a\ b.txt date.txt -exec ./test.sh {} \;
start
file: a b.txt
start
file: date.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.