简体   繁体   English

重击:对包含空格的变量使用cd命令

[英]Bash: use cd command on a variable including spaces

I am attempting to change directory within a script in order to perform a bunch of operations using relative paths. 我试图在脚本中更改目录,以便使用相对路径执行一堆操作。 The folder is a variable named $input_path : 该文件夹是一个名为$input_path的变量:

cd $(echo "$input_path")

If there is a space in the variable, for example "/home/user/test directory/subfolder", the script returns an error: 如果变量中有空格,例如“ / home / user / test directory / subfolder”,脚本将返回错误:

./test_currently_broken.sh: line 86: cd: "/home/user/test: No such file or directory ./test_currently_broken.sh:第86行:cd:“ / home / user / test:没有这样的文件或目录

I have tried various ways to escape the spaces: 我尝试了多种方法来逃避空间:

# escape spaces using backslashes, using sed
input_path=$(echo "$input_path" | sed 's/ /\\ /g')

or 要么

# wrap input path with awk to add quotes
input_path=$(echo "$input_path" | awk '{print "\"" $0 "\""}')

or 要么

# wrap in single quotes using sed
input_path=$(echo "$input_path" | sed -e "s/\(.*\)/'\1'/")#

But none fix the error - it still fails to change directory. 但是没有一个可以解决该错误-它仍然无法更改目录。 I have confirmed that the directory it is attempting to change to definitely exists, and cd ing works outside of this script. 我已经证实,它正试图更改为绝对目录是否存在,以及cd ING工作这个脚本之外。

Is there a solution to this strange behaviour of cd ? 有解决此cd奇怪行为的方法吗?

Why don't you just... 你为什么不...

cd "$input_path"

since it is quoted, there won't be any problem with spaces. 由于已将其引用,因此空格不会有任何问题。

By saying cd $(echo "$input_path") you are in fact saying cd my path , whereas you want to do cd "my path" . cd $(echo "$input_path")实际上是说cd my path ,而您想说cd "my path" Thus, as commented by JID below, you can also say cd "$(echo $input_path)" because the important quotes are the ones that are "closer" to cd . 因此,正如下面的JID所评论的,您也可以说cd "$(echo $input_path)"因为重要的引号是与cd “更近的”。


If you don't quote, cd sees: 如果您不引用, cd看到:

cd my path

So it tries to cd my , whereas if you quote it sees: 因此,它尝试cd my ,而如果您引用它,则会看到:

cd "my path"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM