gpt4 book ai didi

bash - shell脚本通过空格传递参数

转载 作者:行者123 更新时间:2023-12-02 04:16:35 25 4
gpt4 key购买 nike

我有以下脚本(示例):

#!/bin/bash
while getopts a: opt; do
case "$opt" in
a) val="$OPTARG";;
?) echo "use the flag \"-a\""
exit 2;;
esac
done
echo "a specified with: ${val}"

当我现在使用 test.sh -a "here is a string" 调用此脚本时,输出为:a 指定为:here不是 因为我想要指定:这里是一个字符串

我知道我可以使用 test.sh -a here\is\a\stringtest.sh -a "here\is\a\string"< 来调用脚本 就可以了。但就我而言,我无法操纵我想要传递的字符串。
那么如何更改我的 getopts 函数以使其正常工作?

我也尝试过getopt,但我的工作更糟糕:

commandsShort="a:"
commandsLong="aval:"
TEMP=`getopt \
-o $commandsShort \
-l $commandsLong \
-q \
-n "$0" -- "$@"`

我做错了什么?

最佳答案

这个问题在您的问题的评论中得到了解决。 :-)

您正在使用以下方式调用脚本:

eval "test.sh $@"

如果您选择“这里是一个字符串”,则此“eval”行的作用是创建引号中的命令行:

test.sh here is a string

评估评估它。

根据附加评论,如果您可以避免评估,则应该这样做。

也就是说,如果您需要它,您可以随时引用 eval 中的字符串:

eval "test.sh \"$@\""

或者,如果您不喜欢转义引号,请使用单引号,因为由于外部引号是双引号,您的 $@ 将被扩展:

eval "test.sh '$@'"

最后,正如您在评论中提到的,直接运行可能是最好的选择:

test.sh "$@"

注意,如果您的$@包含-a选项,您可能会遇到新问题。考虑命令行:

test.sh "-a here is a string"

在这种情况下,以 -a 开头的整个字符串都可以在 $1 中找到,并且您将没有 getopts 选项,也没有 OPTARG。

关于bash - shell脚本通过空格传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33300076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com