Bash Variables

Just like other languages, Bash has variables. One peculiar thing about variables in Bash is that you access them with the dollar sign, but you set them without it. To clarify, here’s an example:

myvar="Hello world"
echo $myvar

Bash has a number of reserved variables, that are automatically set for you. The following table is a non-exhaustive list of some of the more useful ones:

Variable Function
$0 Name of the current script.
$1 … $9 First 9 arguments to the script.
$# Number of arguments passed to the script.
$@ All the arguments supplied to the script.
$USER The username of the user running the script.
$HOSTNAME The hostname of the machine the script is running on.
$SECONDS The number of seconds since the script was started.
$RANDOM Returns a different random number each time is it referred to.
$LINENO Returns the current line number in the Bash script.

If you liked this page, please share it with a fellow learner: