[英]Ubuntu Bash Script executing a command with spaces
I have a bit of an issue and i've tried several ways to fix this but i can't seem to. 我有一个问题,我尝试了几种方法来解决此问题,但我似乎无法解决。
So i have two shell scripts. 所以我有两个shell脚本。
background.sh : This runs a given command in the background and redirect's output. background.sh :这将在后台运行给定命令并重定向输出。
#!/bin/bash
if test -t 1; then
exec 1>/dev/null
fi
if test -t 2; then
exec 2>/dev/null
fi
"$@" &
main.sh : This file simply starts the emulator (genymotion) as a background process. main.sh :该文件只是作为后台进程启动模拟器(genymotion)。
#!/bin/bash
GENY_DIR="/home/user/Documents/MyScript/watchdog/genymotion"
BK="$GENY_DIR/background.sh"
DEVICE="164e959b-0e15-443f-b1fd-26d101edb4a5"
CMD="$BK player --vm-name $DEVICE"
$CMD
This works fine when i have NO spaces in my directory. 当我的目录中没有空格时,这可以正常工作。 However, when i try to do:
GENY_DIR="home/user/Documents/My Script/watchdog/genymotion"
但是,当我尝试执行以下操作时:
GENY_DIR="home/user/Documents/My Script/watchdog/genymotion"
which i have no choice at the moment. 目前我别无选择。 I get an error saying that the file or directory cannot be found.
我收到一条错误消息,指出找不到文件或目录。 I tried to put
"$CMD"
in quote but it didn't work. 我试图在报价单中加上
"$CMD"
,但没有用。
You can test this by trying to run anything as a background process, doesn't have to be an emulator. 您可以通过尝试将任何东西作为后台进程运行来进行测试,而不必一定是模拟器。
Any advice or feedback would be appreciated. 任何建议或反馈将不胜感激。 I also tried to do.
我也试着做。
BK="'$BK'"
or 要么
BK="\\"$BK\\""
or 要么
BK=$( echo "$BK" | sed 's/ /\\\\ /g' )
Don't try to store commands in strings. 不要尝试将命令存储在字符串中。 Use arrays instead:
改用数组:
#!/bin/bash
GENY_DIR="$HOME/Documents/My Script/watchdog/genymotion"
BK="$GENY_DIR/background.sh"
DEVICE="164e959b-0e15-443f-b1fd-26d101edb4a5"
CMD=( "$BK" "player" --vm-name "$DEVICE" )
"${CMD[@]}"
Arrays properly preserve your word boundaries, so that one argument with spaces remains one argument with spaces. 数组正确保留了单词边界,因此一个带空格的参数仍然是一个带空格的参数。
Due to the way word splitting works, adding a literal backslash in front of or quotes around the space will not have a useful effect. 由于分词的工作方式,在空格前面或引号内添加文字反斜杠将不会产生有用的效果。
John1024 suggests a good source for additional reading: I'm trying to put a command in a variable, but the complex cases always fail! John1024提供了一个很好的参考资料来源: 我试图将命令放入变量中,但是复杂的情况总是会失败!
try this: 尝试这个:
GENY_DIR="home/user/Documents/My\ Script/watchdog/genymotion"
You can escape the space with a backslash. 您可以使用反斜杠转义空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.