Preface
It is well known that variables in the Shell only act on the current process. To create a copy in a child process, use the export built-in command. Sometimes using temporary variable syntax can be very convenient.
Variable usage
- Shell variables can be defined anywhere, using = to separate variable names and variable values. = There are no spaces before and after, but the value of the variable can be left blank.
- Reading variables requires the $ prefix.
- The variable scope is the current process.
For example:
url= echo $url
export to child process
Usually variables do not need export, but when you need to divide a work into small tasks and implement them with a script, you need to pass the variable names to them. For example, there is a way to download any URL to the temporary directory:
#!/usr/bin/env bash curl $url > $TMPDIR/$
We need to pass the url in the current script to:
export url= bash ./ # Equivalent to (if the file has executable permissions)./
It is worth noting that export will only create copies of variables in the child process, that is, changes to it will not be reflected in the current process.
Execute scripts in the current process
Use source or . built-in commands to execute another script in the current process, so variables in the current context are visible to the script.
url= source ./ # is equivalent to. ./
Temporarily set environment variables
According to Shell syntax, any assignment statement can be included before a simple command. These variable assignments will be expanded before executing the command, equivalent to temporary environment variables.
A “simple command” is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator. – Simple Commands, Shell Commands
For example, the following command can pass the url variable to:
url= bash ./
This is a simple command, the following multiple commands or combination commands:
url=; bash ./ # Two commands only apply to the current processurl= && bash ./ # Combination commands, only acting on the current processexport url=; bash ./ # Two commands,Effects on the father-son process
Variable assignments in simple commands also do not act on the current process. For example, the following code will output empty lines:
url= echo $url
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.