BASE_DIR_APP_CONN="/opt/"
CMD_CONFIG_SNAPSHOT_DIR_APP_CONN="ls -ltrh $BASE_DIR_APP_CONN/local/ | awk '{print \$NF}' | tail -n 2 | xargs"
echo $CMD_CONFIG_SNAPSHOT_DIR_APP_CONN
for dir in $($CMD_CONFIG_SNAPSHOT_DIR_APP_CONN)
do
echo "$dir"
done
為什么這會引發以下錯誤:
ls: cannot access |: No such file or directory
ls: cannot access awk: No such file or directory
ls: cannot access '{print: No such file or directory
ls: cannot access $NF}': No such file or directory
ls: cannot access |: No such file or directory
ls: cannot access tail: No such file or directory
ls: cannot access 2: No such file or directory
ls: cannot access |: No such file or directory
ls: cannot access xargs: No such file or directory
/opt/local/:
.....
當我直接使用命令運行 for 回圈時,它按預期作業。有人可以幫忙嗎?謝謝 !
uj5u.com熱心網友回復:
在引數擴展之前完成將字串拆分為單獨的命令(即,通過|,; 等等) 。所以,
foo | bar
運行foo和bar,由管道連接。然而,
nonsense="foo | bar"
$nonsense
foo使用兩個引數|和呼叫命令bar。為了運行存盤到變數中的管道,我必須撰寫類似的東西
eval "$nonsense"
但總的來說,這是一個壞主意,尤其是因為您遲早會遇到參考和空格問題的麻煩(如果您使用字串嘗試此操作,您會看到)。
在你的情況下,我會使用一個函式,例如:
CMD_CONFIG_SNAPSHOT_DIR_APP_CONN() {
ls -ltrh $BASE_DIR_APP_CONN/local/ | awk '{print \$NF}' | tail -n 2 | xargs
}
并將其稱為
for dir in $(CMD_CONFIG_SNAPSHOT_DIR_APP_CONN)
當然,這仍然存在幾個問題,例如決議輸出ls并將其輸入awk(如果目錄條目包含空格字符,這將中斷),但這不是您問題的主題,所以我就這樣離開了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522995.html
標籤:重击壳
