Shell and eval are implemented by obtaining environment variables through variables

Time:2021-9-16

scene

  • The environment variable user = iceber exists in the system
  • There is a variable env in the script_ name=USER
  • You need to pass the variable env_ Name gets the value of the environment variable user

Error example

Environment variable user already exists in $# environment
$ env_name=USER
$ echo ${$env_name}
${$env_name}: bad substitution

Obviously, it doesn’t work to get values directly using $nesting

Correct example

Environment variable user already exists in $# environment
$ env_name=USER
$ eval echo '$'$env_name
icebergu

Eval will first replace the parameters with variables, and then execute the parameters as commands


eval echo '$'$env_naem
  • First, $env_ Name is replaced by user. At this time, the string $user will be formed with the previous’ $’, and the current command has actually become Eval echo $user
  • Then Eval executes echo $user, which completes the acquisition of environment variables

According to the above analysis, it can be found that the command can actually be written as Eval echo \ $$env_ Name is OK, too

Similarly, if a variable contains the names of other variables, the value of the corresponding variable can also be obtained by using eval

This is the end of this article about the implementation of shell Eval’s method of obtaining environment variables through variables. For more information about shell Eval’s method of obtaining environment variables, please search for previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]