在Bash中扩展变量中的变量

时间:2014-07-22 02:29:35

标签: bash shell variables scripting

我有一个脚本,我需要传递一个字符串,其中包含变量和文本以符合URI。

这方面的一个例子是:

URI="${PROTO}://${USER}:${PASS}@${HOST}/${TARGET}"

我定义变量${PROTO}时未定义变量${USER}${PASS}${HOST}${TARGET}$URI但它们将会定义当要执行Bash脚本时,我需要将URI扩展为字符串的最终形式。

我该怎么做?我已经阅读了eval: When You Need Another Chance但我真的不喜欢使用eval,因为它可能是危险的,而且它意味着要逃避URI字符串的很多部分。

还有其他办法吗?该问题的推荐解决方案是什么?

由于 中号

2 个答案:

答案 0 :(得分:3)

变量存储数据;如果你没有PROTO等人的价值观。然而,你没有数据。你需要一个模板。

uri_template="%s://%s:%s@%s/%s"

稍后,当包含其余数据时,您可以将它们插入到模板中。

uri=$(printf "$uri_template" "$PROTO" "$USER" "$PASS" "$HOST" "$TARGET")

(在bash中,您可以使用-v选项printf -v uri "$uri_template" "$PROTO" "$USER" "$PASS" "$HOST" "$TARGET"来避免使用命令替换fork。)

您还可以定义一个功能:

uri () {
    # I'm being lazy and assuming uri will be called with the correct 5 arguments
    printf "%s://%s:%s@%s/%s" "$@"
}

# Variables and functions exist in separate namespaces, so the following works
uri=$(uri "$PROMPT" "$USER" "$PASS" "$HOST" "$TARGET")

答案 1 :(得分:3)

在执行脚本之前,使用' export'。

定义变量
export PROTO='http'
export USER='bob'
export PASS='password'
export HOST='myhostname'
export TARGET='index.html'

bash ./myscript_with_uri.sh

OR

创建URI脚本作为将返回URI的过程。

uri_creater.sh

makeUri ()
{
    URI="${PROTO}://${USER}:${PASS}@${HOST}/${TARGET}
}

script_using_uri.sh

. uri_creater.sh
PROTO='http'
USER='bob'
PASS='password'
HOST='myhostname'
TARGET='index.html'

makeUri

url="${URI}"

echo "${url}"

使用bash在Centos 6.5上测试。

相关问题