我对文件系统的访问权限有限,我想设置通用通知处理程序调用:
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)作为消息发送到电报机器人,但是试图简化这种情况。
答案 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
的命令,甚至可能在脚本运行之前生成错误。请改用${var}
。
要使此方法有效,我们需要在$3
中重命名变量。
envsubst
是GNU gettext-base
包的一部分,默认情况下应该可用于Linux发行版。
帽子提示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