通过对您的$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