【发布时间】:2015-04-23 18:50:53
【问题描述】:
我正在尝试更改脚本中的目录,以便使用相对路径执行一系列操作。该文件夹是一个名为$input_path的变量:
cd $(echo "$input_path")
如果变量中有空格,例如“/home/user/test directory/subfolder”,脚本返回错误:
./test_currently_broken.sh:第 86 行:cd:“/home/user/test:没有这样的 文件或目录
我尝试了各种方法来逃避空格:
# 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'/")#
但没有人修复错误 - 它仍然无法更改目录。
我已确认它尝试更改为肯定的目录存在,并且cding 在此脚本之外工作。
cd这种奇怪的行为有解决办法吗?
【问题讨论】:
-
不是 cd 行为异常,实际上什么都没有。您没有引用子外壳,因此您所在的外壳扩展了从它返回的内容。所以无论你在 subshell 中做什么都是无关紧要的。