Ubuntu Bash脚本用空格执行命令

时间:2016-07-22 20:55:37

标签: linux bash

我有一些问题,我已经尝试了几种方法来解决这个问题,但我似乎无法做到。

所以我有两个shell脚本。

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 :此文件只是启动模拟器(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

当我的目录中没有空格时,这很好用。但是,当我尝试这样做时:GENY_DIR="home/user/Documents/My Script/watchdog/genymotion"

目前我别无选择。我收到一条错误消息,指出无法找到该文件或目录。我尝试将"$CMD"引用,但它没有用。

您可以尝试将任何内容作为后台进程运行来测试,不必是模拟器。

任何建议或反馈都将不胜感激。我也试过。

BK="'$BK'"

BK="\"$BK\""

BK=$( echo "$BK" | sed 's/ /\\ /g' )

2 个答案:

答案 0 :(得分:4)

不要尝试将命令存储在字符串中。改为使用数组:

#!/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[@]}"

数组正确保留了单词边界,因此带空格的一个参数仍然是带空格的一个参数。

由于单词拆分的工作方式,在空格前面添加文字反斜杠或在空格周围添加引号不会产生有用的效果。

John1024提供了额外阅读的良好来源:I'm trying to put a command in a variable, but the complex cases always fail!

答案 1 :(得分:-2)

试试这个:

GENY_DIR="home/user/Documents/My\ Script/watchdog/genymotion"

你可以用反斜杠逃避空间。

相关问题