bash 如何在bash shell脚本中容纳变量中的空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4952120/
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-17 23:25:59  来源:igfitidea点击:

How to accommodate spaces in a variable in a bash shell script?

bashvariablesspaceunicode-escapes

提问by Bala

Hopefully this should be a simple one... Here is my test.sh file:

希望这应该是一个简单的...这是我的 test.sh 文件:

#!/bin/bash
patch_file="/home/my dir/vtk.patch"
cmd="svn up \"$patch_file\""
$cmd

Note the space in "my dir". When I execute it,

注意“我的目录”中的空格。当我执行它时,

$ ./test.sh 
Skipped '"/home/my'
Skipped 'dir/vtk.patch"'

I have no idea how to accommodate the space in the variable and still execute the command. But executing this the following on the bash shell works without problem.

我不知道如何容纳变量中的空间并仍然执行命令。但是在 bash shell 上执行以下操作没有问题。

$ svn up "/home/my dir/vtk.patch"   #WORKS!!!

Any suggestions will be greatly appreciated! I am using the bash from cygwin on windows.

任何建议将不胜感激!我在 Windows 上使用来自 cygwin 的 bash。

回答by Kevin Beck

Use eval $cmd, instead of plain $cmd

使用 eval $cmd,而不是普通的 $cmd

回答by Dave

Did you try escaping the space?
As a rule UNIX shells don't like non-standard characters in file names or folder names. The normal way of handling this is to escape the offending character. Try:

你有没有尝试逃离空间?
通常,UNIX shell 不喜欢文件名或文件夹名中的非标准字符。处理这个问题的正常方法是逃避有问题的角色。尝试:

patch_file="/home/my\ dir/vtk.patch"

Note the backslash.

注意反斜杠。