如何用Bash中另一个变量的值替换变量中的占位符或单词? [英] How to replace placeholder character or word in variable with value from another variable in Bash?

查看:81
本文介绍了如何用Bash中另一个变量的值替换变量中的占位符或单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的Bash脚本.我有一个简单的模板"变量:

I'm trying to write a simple Bash script. I have a simple "template" variable:

template = "my*appserver"

然后,

我有一个函数(get_env()),该函数返回值devqalive.我想调用get_env,然后将template变量用get_env的返回值替换为字符串,然后将其替换为星号.所以:

I then have a function (get_env()) that returns the values dev, qa, or live. I'd like to call get_env and then string-replace the template variable with get_env's return value and swap it out with the asterisk. So:

# Returns "dev"
server = get_env

# Prints "mydevappserver"
template = string_replace(server, template)

或者:

# This time, it returns "live"
server = get_env

# Prints "myliveappserver"
template = string_replace(server, template)

我应该使用什么代替此string_replace()函数来完成绑定?

What should I be using in lieu of this string_replace() function to accomplish the binding?

推荐答案

Bash可以自己进行字符串替换:

Bash can do string replacement by itself:

template='my*appserver'
server='live'
template="${template/\*/$server}"

有关字符串替换的更多详细信息,请参见高级bash脚本指南.

See the advanced bash scripting guide for more details on string replacement.

对于bash函数:

function string_replace {
    echo "${1/\*/$2}"
}

要使用:

template=$(string_replace "$template" "$server")

这篇关于如何用Bash中另一个变量的值替换变量中的占位符或单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆