我正在嘗試更改腳本中的目錄以便使用相對路徑執行一堆操作。該文件夾是一個變量命名$input_path
:Bash:在包含空格的變量上使用cd命令
cd $(echo "$input_path")
如果在變量的空間,例如 「/ home/user中/ test目錄/子文件夾」,該腳本返回一個錯誤:
./test_currently_broken.sh: line 86: cd: "/home/user/test: No such file or directory
我已經想盡各種辦法逃避的空間:
# escape spaces using backslashes, using sed
input_path=$(echo "$input_path" | sed 's/ /\\ /g')
或
# wrap input path with awk to add quotes
input_path=$(echo "$input_path" | awk '{print "\"" $0 "\""}')
或
# wrap in single quotes using sed
input_path=$(echo "$input_path" | sed -e "s/\(.*\)/'\1'/")#
但沒有修復這個錯誤 - 它仍然不能改變目錄。 我已經確認它試圖更改爲的目錄肯定存在,並且cd
ing在此腳本之外有效。
有沒有解決這個奇怪的行爲cd
?
這不是CD是行爲奇怪的是,事實上並沒有什麼。您沒有引用subshell,因此您所在的shell擴展了它所返回的內容。所以無論你在子shell中做什麼都是無關緊要的。 – 2015-04-23 10:32:30