Original link: http://www.361way.com/shell-eval-variable/4957.html
Nesting of variables is often used in the shell. For example, the value of a single or multiple variables as a variable name, and then the variable name to get its internal variables, this script is difficult to write, fortunately there is an eval command to facilitate our handling of this situation. Easy to understand, let's start with an example:
- #!/bin/bash
- A=' my '
- b=' site '
- My_site=' My site www.361way.com '
- Echo A_b is "$a"_"$b"
- echo $("$a"_"$b")
- Web="$a"_"$b"
- echo Web is $web
- Eval echo ' $ ' "$a"_"$b"
- Eval echo ' $ '{"$a"_"$b"}
Like the example above, guess what it's running for? The results of the implementation are as follows:
- # sh a.sh
- A_b is My_site
- A. SH: line 6: my_site: command not found
- Web is My_site
- My Site www. 361way. COM
- My Site www. 361way. COM
From the above can be seen $ ("$a" _ "$b") This writing will be error, you can correctly take the results we want can be written in two ways: eval echo ' $ ' $a "_" $b "or eval echo ' $ ' {" $a "_" $b "}.
Eval is so magical, what the hell is it?
The eval command will first scan the command line for all permutations before executing the command. This command applies to variables that scan for a variable that does not function at one time, and the command scans the variables two times. These variables, which need to be scanned two times, are sometimes referred to as complex variables. The eval command can be used to echo a simple variable, or to echo a complex variable.
Another example, in this case, the file has two columns, the first column variable name, the second column variable value, after reading the file, the value of the second row is assigned to the first column, through the Echo ${column name}, you can get the value of the subsequent value. As follows:
- Variable name and variable Value mapping table:
- # more Name_value.txt
- Site www. 361way. COM
- mail [email protected]. COM
- User admin
- Script content:
- # Cat B.sh
- #!/bin/bash
- While read NAME VALUE
- Do
- eval "${name}=${value}"
- Done < name_value. TXT
- echo "$site $mail $user"
Execute the script with the following results:
- # sh b.sh
- www. 361way. com [email protected]. COM admin
Variables in the shell and Eval (go)