如何在 Bash 变量中添加带空格的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43787476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:07:18  来源:igfitidea点击:

How to add path with space in Bash variable

bashterminal

提问by Mohamed ?Radwan

How can I add a path with a space in a Bash variable in .bashrc? I want to store some variables in .bashrcfor paths and I encountered a path with a space in it.

如何在 Bash 变量中添加带有空格的路径.bashrc?我想在.bashrc路径中存储一些变量,但我遇到了一个带有空格的路径。

I tried to add it between ' 'or use the escape character \, but it didn't help:

我试图在它们之间添加' '或使用转义字符\,但它没有帮助:

games=/run/media/mohamedRadwan/games\ moves    # this doesn't work
games='/run/media/mohamedRadwan/games  moves'  # or this
games="/run/media/mohamedRadwan/games  moves"  # or this

... when I run:

...当我跑:

mount $games

... it throws an error indicating that it's only trying to mount /run/media/mohamedRadwan/games.

...它抛出一个错误,表明它只是试图 mount /run/media/mohamedRadwan/games

But when I run echo $games, it shows the full value, /run/media/mohamedRadwan/games moves.

但是当我运行时echo $games,它显示了完整的值,/run/media/mohamedRadwan/games moves.

How can I solve this?

我该如何解决这个问题?

采纳答案by bishop

mount /dev/sda9 "$games"

As mentioned, always quote variable dereferences. Otherwise, the shell confuses the spaces in the variable's value as spaces separating multiple values.

如前所述,始终引用变量解引用。否则,shell 会将变量值中的空格混淆为分隔多个值的空格。

回答by Nahuel Fouilleul

When variable contains spaces, variable expansion and then word splitting will result to many arguments, echo command will display all arguments but other program or function may handle arguments another way.

当变量包含空格时,变量扩展然后分词会导致许多参数,echo 命令将显示所有参数,但其他程序或函数可能会以另一种方式处理参数。

Surrounding variable with double quotes will prevent arguments to be splitted

带双引号的环绕变量将防止参数被拆分

printf "'%s'\n" $games

printf "'%s'\n" "$games"