bash how to use variables


Firstly, you have to declare a variable:


To get value from variable use the symbol "$" before variable name like in the following example:

echo $var friends.

Output: Hello friends.

Curly brackets "{}" are used to expand variable in the string. Often use to append string after variable value:

echo ${var}ween

Output: Helloween

If we did't use "{}" around var, echo would only write empty line.

There are examples of special variables:
$0 - Name of the bash script.
$# - How many arguments were passed to script.
$? - Exit code of the last run process.
$$ - Process ID of the actual script.
$HOSTNAME - Hostname of the machine that script is running on.
$LINENO -Current line number in the script.

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.