如何插入作为参数发送的字符串?

时间:2018-03-16 21:30:11

标签: shell command-line-arguments string-interpolation

我对文件系统的访问权限有限,我想设置通用通知处理程序调用:

notificator.sh "apples" "oranges" "There were $(1) and $(2) in the basket"

notificator.sh内容:

#!/bin/sh
echo $3

输出如下:

"There were apples and oranges in the basket"

有可能吗?我更喜欢它是否是内置的解决方案。 我实际上是尝试通过curl post param将结果字符串($ 3)作为消息发送到电报机器人,但是试图简化这种情况。

1 个答案:

答案 0 :(得分:3)

$3进行一些更改后,我们可以轻松完成此工作。

首先,让我们定义$1$2$3

$ set -- "apples" "oranges" 'There were ${one} and ${two} in the basket'

现在,让我们强行替换$3

$ one=$1 two=$2 envsubst <<<"$3"
There were apples and oranges in the basket

注意:

  1. $(1)尝试运行名为1的命令,甚至可能在脚本运行之前生成错误。请改用${var}

  2. 要使此方法有效,我们需要在$3中重命名变量。

  3. envsubst是GNU gettext-base包的一部分,默认情况下应该可用于Linux发行版。

  4. 帽子提示Charles Duffy

    以脚本形式

    考虑这个脚本:

    $ cat script.sh
    #!/bin/sh
    echo "$3" | one=$1 two=$2 envsubst
    

    我们可以执行以上内容:

    $ sh script.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
    There were apples and oranges in the basket
    

    作为替代方案(再次提到Charles Duffy),我们可以使用here-doc:

    $ cat script2.sh
    #!/bin/sh
    one=$1 two=$2 envsubst <<EOF
    $3
    EOF
    

    运行此版本:

    $ sh script2.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
    There were apples and oranges in the basket
    

    替代

    以下脚本不需要envsubst

    $ cat script3.sh
    #!/bin/sh
    echo "$3" | awk '{gsub(/\$\{1\}/, a); gsub(/\$\{2\}/, b)} 1' a=$1 b=$2
    

    使用我们的参数运行此脚本,我们发现:

    $ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
    There were apples and oranges in the basket
    $ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
    There were apples and oranges in the basket