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

Mel*_*son 5 shell string-interpolation command-line-arguments

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

notificator.sh "apples" "oranges" "There were $(1) and $(2) in the basket"
Run Code Online (Sandbox Code Playgroud)

notificator.sh内容:

#!/bin/sh
echo $3
Run Code Online (Sandbox Code Playgroud)

并得到如下输出:

"There were apples and oranges in the basket"
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*024 4

通过对您的 进行一些更改$3,我们可以轻松地完成这项工作。

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

$ set -- "apples" "oranges" 'There were ${one} and ${two} in the basket'
Run Code Online (Sandbox Code Playgroud)

现在,让我们强制替换为$3

$ one=$1 two=$2 envsubst <<<"$3"
There were apples and oranges in the basket
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. $(1)尝试运行名为1and 的命令可能会在脚本运行之前生成错误。${var}代替使用。

  2. 为了让这个方法发挥作用,我们需要重命名$3.

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

向查尔斯·达菲致敬。

以脚本形式

考虑这个脚本:

$ cat script.sh
#!/bin/sh
echo "$3" | one=$1 two=$2 envsubst
Run Code Online (Sandbox Code Playgroud)

我们可以执行上面的命令:

$ sh script.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket
Run Code Online (Sandbox Code Playgroud)

作为替代方案(再次向Charles Duffy致敬),我们可以使用此处文档:

$ cat script2.sh
#!/bin/sh
one=$1 two=$2 envsubst <<EOF
$3
EOF
Run Code Online (Sandbox Code Playgroud)

运行这个版本:

$ sh script2.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket
Run Code Online (Sandbox Code Playgroud)

选择

以下脚本不需要envsubst

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

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

$ 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
Run Code Online (Sandbox Code Playgroud)