简体   繁体   中英

Read different lines from a text file and set different variables in bash shell

I have a text file with different lines like:

VMNAME-1="blah1"
VMANME-2="blah2"
VMIP-1=12.34.56.78
VMIP-2=98.76.54.32
PASS="something"
USER="else"

and I want to read this text file and use these values in a bash shell in lines like this:

create_vm.exp VMIP-1 USER PASS VMNAME-1
create_vm.exp VMIP-2 USER PASS VMNAME-2

any suggestion about how to do that?

Like earlier comments stated, You should
Simply use source /path/to/file And execute your script,
Since your text file's syntax is just like a variable initialization.

Explanation

Sourcing actually runs the file you're trying to source in your current
Bash enviroment.
When you open a terminal and source the text file, you could use
The variables you've set, like $USER, $PASS, etc..
And you can do the same inside your script, to execute other scripts.

If the symbol names on the left side of the equal signs hadn't contained a - , then you could simply source the script, as all the lines would be valid Bash expressions.

However, that is not the case here, as VMNAME-1 and others do contain a - , and so VMNAME-1 is not a valid variable name in Bash.

If you know for certain that none of the values after the equal sign will contain - , then you could simply replace all occurrences of - with _ to make the lines valid Bash expressions like this:

. <(tr -- - _ < input.txt)

And then you could write the create VM commands like this:

create_vm.exp "$VMIP_1" "$USER" "$PASS" "$VMNAME_1"
create_vm.exp "$VMIP_2" "$USER" "$PASS" "$VMNAME_2"

If the values may contain - , then you need to work a bit harder to replace - only at the left side of the equal sign. Here's a possible simple workaround that would work in some cases, but maybe not all:

. <(sed -e '/^V/s/-/_/' < input.txt)

This replaces - only on lines that start with V , and only the first occurrences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM