Bash How to Use Variables

Bash How to Use Variables

Firstly, you have to declare a variable:

var="Hello"

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 variables in the string. Often use to append string after variable value:

echo ${var}ween

Output: Helloween

If we didn’t use “{}” around var, the echo would only write an empty line.

There are examples of special variables:

  • $0 – Name of the bash script.
  • $# – How many arguments were passed to the 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.

Leave a Comment