构造需要引号

时间:2018-04-24 14:23:52

标签: bash shell quotes

我有一个Bash脚本需要调用一个命令,该命令需要其中一个参数的引号。当我运行命令

myTimeCommand --time="2018 04 23 1100" -o /tmp/myOutput ~/myInput

从命令行,它工作正常。在我的脚本中,我想传递“2018 04 23 1100”作为参数并将其直接发送到命令。

myScript --time="2018 04 23 1100"

但是,当我尝试这个时,我收到一条错误消息

""2018" is not a valid time.

我正在使用getopt来解析参数。这是我的剧本

OPTIONS=t:
LONGOPTIONS=time:

PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")
echo ${PARSED}

# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"

# now enjoy the options in order and nicely split until we see --
while true; do
    echo "option: ${1}"
    case "$1" in
        -t|--time)
            timeBase="$2"
            timeBase="--time=\"${timeBase}\""
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Programming error"
            exit 3
            ;;
    esac
done

echo ${timeBase}

myTimeCommand ${timeBase} -o /tmp/myOutput ~/myInput

编辑:删除了runCommand()功能。虽然这产生了一些好的评论,但减损了手头的问题 - 复制引用的参数以使用命令运行。

第二个例子:

的文本文件(myTest.txt
I have a Bash script that needs to call a command that will require quotes for one of it's arguments.  When I run the command

myTimeCommand --time="2018 04 23 1100" -o /tmp/myOutput ~/myInput

from the command line, it works fine.  In my script, I want to pass "2018 04 23 1100" as a parameter and send it directly to the command.

当我运行grep "command line" myTest.txt时,我得到了最后一行的命中(正如预期的那样)。当我将脚本修改为

OPTIONS=s:
LONGOPTIONS=str:

PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")

echo ${PARSED}

# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"

# now enjoy the options in order and nicely split until we see --
while true; do
    echo "option: ${1}"
    case "$1" in
        -s|--str)
            sStr="\"$2\""
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Programming error"
            exit 3
            ;;
    esac
done

echo "grep ${sStr} myTest.txt"

grep ${sStr} myTest.txt

echo按预期显示命令,但实际的grep失败

-bash-4.2~>./extText --str="command line"
grep "command line" myTest.txt
grep: line": No such file or directory

如何使用传入的参数调用grep(在本例中为“命令行”)?

1 个答案:

答案 0 :(得分:5)

不要使用变量来运行命令!它们用于保存数据而不是功能。使用数组

cmdArray=()
cmdArray=( "myTimeCommand" "${timeBase}" "-o" "/tmp/myOutput" "~/myInput" )

并传递引用的数组以防止分词

runCommand "${cmdArray[@]}"

请参阅BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!