【问题标题】:How to replace a variable and then execute the command如何替换变量然后执行命令
【发布时间】:2019-01-08 14:24:56
【问题描述】:

我正在尝试创建一个 shell 脚本来检索所有 JIRA 问题的值并将其存储在一个文件中。在这里,我希望能够在执行之前解释变量的值。

我已经尝试了几种替代方法,并且已经用尽了所有选择。我使用单引号、双引号甚至转义字符作为美元符号。即使是 exec 命令,但它们都不起作用

var1="project in (ELIP)"

./jira.sh --action getIssueList --jql "$var1"  --columns "Key" --outputFormat 999  --file "/root/scripts/getList.txt" 

注意:命令 ./jira.sh 要求 --jql 参数用双引号括起来。

我希望$var1 的值应该首先被解释,然后./jira.sh 命令应该运行。但我无法让它工作。

【问题讨论】:

  • 为什么 jira.sh 期望 --jql 的参数包含引号? “解释”是什么意思?
  • 这看起来不错。如果您需要双引号,则需要转义它们,例如"\"$var1\"".
  • 我发布了一个答案。如果您想了解更多详细信息,请说明您正在运行哪个 shell(sh、bash、ksh)、哪个版本以及 jira.sh 做了什么
  • 谢谢布鲁诺雷。如果我使用 exec 命令运行它,它可以工作,但没有 exec 它不会。 exec ./jira.sh --action getIssueList --jql "$var1" --columns "Key" --outputFormat 999 --file "/root/scripts/updateFieldEllipse/getList.txt" ---工作但./jira .sh --action getIssueList --jql "$var1" --columns "Key" --outputFormat 999 --file "/root/scripts/updateFieldEllipse/getList.txt" 不起作用
  • 我很高兴你让它工作。您的评论不是 100% 清楚,如果您想要更好的答案,请编辑您的问题,准确添加哪些有效,哪些无效。

标签: shell sh


【解决方案1】:

好吧,我不知道 jira.sh 到底是做什么的,但这里有一些关于 shell 变量的解释(用 bash 测试过,其他 shell 可能表现不同):

首先使用一个测试脚本来告知如何接收参数:

$ cat test.sh 
#!/bin/bash
echo arg1: $1
echo arg2: $2
echo arg3: $3

现在,如果我们使用文字文本参数(无变量)运行

$ ./test.sh arg_no_1 'multiple words argument' arg_no_3
arg1: arg_no_1
arg2: multiple words argument
arg3: arg_no_3

现在我们定义我们的变量(用单引号)

$ variable='multiple words variable'

如果你不带引号运行你会得到一个错误的输出,变量会在 bash 中扩展并占用下一个参数的槽:

$ ./test.sh arg_no_1 $variable arg_no_3
arg1: arg_no_1
arg2: multiple
arg3: words

如果我们尝试用简单的引号括起来,变量将不会被解释,而是作为文字发送到脚本。

$ ./test.sh arg_no_1 '$variable' arg_no_3
arg1: arg_no_1
arg2: $variable
arg3: arg_no_3

但是用双引号括起来会产生预期的结果:

$ ./test.sh arg_no_1 "$variable" arg_no_3
arg1: arg_no_1
arg2: multiple words variable
arg3: arg_no_3

您应该阅读报价用法。简短的解释:在 shell 中,单引号 ' 被视为文字内容,其中的变量不会被解释。双引号" 被视为要解释的内容,其中的变量被替换为它们的值。这是tldp 上有关报价的一些信息。另外,gnu.org 有信息。

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多