I'm trying to write a simple Bash script. I have a simple "template" variable:
template = "my*appserver"
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)
Or:
# This time, it returns "live" server = get_env # Prints "myliveappserver" template = string_replace(server, template)
What should I be using in lieu of this string_replace()
function to accomplish the binding?
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.
Bash can do string replacement by itself:
template='my*appserver' server='live' template="${template/\*/$server}"
See the advanced bash scripting guide for more details on string replacement.
So for a bash function:
function string_replace { echo "${1/\*/$2}" }
And to use:
template=$(string_replace "$template" "$server")
String replacement in a bash-script can e.g. be achieved by sed:
template=$(echo $template | sed 's/old_string/new_string/g')
This will replace old_string with new_string in the template variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With