- Variables can be created and assigned text using an equals sign.
Surround the text with double quotes (although it is not necessary unless there is space in the name):
$ FILENAME="info.txt"
$ printf “%s\n” “$FILENAME”
info.txt
- The declare command, in addition to creation of variable and assigning values, can add attributes to variables as well
(using + instead of - turns of the attribute).
declare -r x=5
(-r option makes the variable read-only)
The declare command without any options list all pre-defined variables of system.
- The results of a command can be assigned to a variable using backquotes.
$ Date=`date`
$ printf "%s\n" "$Date"
Thu Apr 13 08:02:19 UTC 2017
- Double quotes do not prevent Bash from interpreting the special characters $, ‘, and \, but single quotes leave all characters unchanged.
- Variable names can be enclosed in curly braces to make it clear where the variable’s name begins and ends.
$ TAX_MESSAGE="The tax is ${TAX}%" - Shell variables exist in the script or interactive sessions only, where they were declared. In order to make shell variables available outside of their place of origin, they have to be declared as exportable with -x option.
Although Linux has provisions for exporting environment variables, there is no way to assign any attributes to them.
The variables shared with a new program are copies of the original. If a script declares an exported variable and runs a second script, any changes made to the variable by the second script are invisible to the first.There is no way for a second script to assign a new value to a variable that the first script will see. Unlike other programming languages, exporting shell variables is a one-way street.
The only way to return a value to the calling program is to write it to a file (or standard output) and have the calling program read (or assign) the value back into a variable.- Before a command is executed, Bash searches the command for all dollar signs and inserts the value of variables before the command is carried out. Bash performs this substitution once. eval command do this another time:
#!/bin/bash
VAR1=25
VAR2='$VAR1'
VAR3='$VAR2'
echo "$VAR3"
eval echo "$VAR3"
eval eval echo "$VAR3"
Output of the script above:
$VAR2
$VAR1
25 - Shell variables exist in the script or interactive sessions only, where they were declared. In order to make shell variables available outside of their place of origin, they have to be declared as exportable with -x option.
$RANDOM | Generates a random integer number (0 - 32767) |