Shell and variables
How to use variables in the shell
✔️ Working with variables
- The shell suports 2 types of variables : environment variables and shell variables
- Environment variables
- Environment variables are available system-wide and are inherited by all spawned child processes and shells.
- Their values differ from user to user (an obvious example is
$USER
) - They can be modified, or new variables can be added with the syntax
env VARIABLE=value
- Shell variables
- Shell variables are variables that apply only to the current shell instance.
- Each shell (zsh, bash, etc ...) has its own set of predefined internal shell variables.
- They can be modified, or new variables can be added with the syntax
set VARIABLE=value
Similar to shell commands, environment variables are accessibles from within shell scripts
✔️ List of predefined environment variables :
environment | contains |
---|---|
$0 |
the name of the running executable |
$1 - $9 |
the first 9 arguments that were passed to it |
$# |
total number of arguments that were passed |
$@ |
all the arguments that were passed |
$? |
the exit status of the most recently run process |
$$ |
the PID (process id) of the current executable instance |
$USER |
the username of the user running the process |
$HOSTNAME |
the hostname of the machine the process is running on |
$SECONDS |
the number of seconds since the process has started |
$RANDOM |
returns a different random number each time is it referred to |
$LINENO |
returns the current line number in the context of the shell or script |
✔️ User-defined variables
- User defined variables are most often used in shell scripts
- A variable is set with the following syntax
VARIABLE=value
(no space on either side of the equals sign) - A variable is referred to with the following syntax
$VARIABLE
- Any variable included in a command will have the shell command substitution replace it with its value prior to actually running the command
- The scope of a variable is the process it is created in : having the same variable referenced in 2 different scripts requires the variable to be exportd as an environment variable
- Setting an environment variable in a script won't change its value outside of the script unless it is exported again.
✔️ Working with lists
- Lists are actually list of words that can either be :
- A series of strings, separated by spaces, ex :
Stan Kyle Cartman
- A range of numbers, separated by 2 dots, ex :
{1..5}
or{10..0}
- It will evaluate as an increasing series of numbers if the right value is greater than the left value
- It will evaluate as a decreasing series otherwise ...
- It is also possible to specify the increase/decrease value to by adding two more dots (..) and the value to use
- For example,
{10..0..2}
will evaluate to10 8 6 4 2 0
- A series of strings, separated by spaces, ex :
- lists are not arrays : for instance range numbers can't be assigned to variables without being expanded into an array first