我正在尝试更改脚本中的目录以便使用相对路径执行一堆操作。该文件夹是一个变量命名$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