Bash Variable Tutorial

Linux bash is a command-line interface and programming interface for the Linux, Unix even MacOS operating systems. One of the most popular and useful features of the bash environment is the variables. Bash variables are used to store different data and information for the current user, processes, system, databases, etc.

Define Bash Variable

Variables can be defined easily in a bash environment by just assigning values to the variables with equal signs. The bash variable define-syntax is like below.

VARIABLE = VALUE

In the following example, we will create a variable named msg and put the value as Hello World .

msg="Hello World"

Print Bash Variable Value

Bash variables can be accessed by using the $ operator before their names. The echo command can be used to print the variable value easily. In order to print the bash variable named msg we use the $msg to express the msg variable.

echo $msg
Hello World

Also, we can print the values of the variables inside double quotes or strings like below.

$age=10

echo "You are $age years old."

Update Bash Variable

During this time the bash variable value can be changed or updated. The variable update is the same as the variable definition where the variable new value is set with the equal sign.

msg="Hello World"

echo $msg

msg="Hello LinuxTect"

echo $msg

Special Variables

Even users and applications can create variables also there are some special variables provided by the bash.

  • $0 – The name of the Bash script.
  • $1 – $9 – The first 9 arguments to the Bash script. (As mentioned above.)
  • $# – How many arguments were passed to the Bash script.
  • $@ – All the arguments supplied to the Bash script.
  • $? – The exit status of the most recently run process.
  • $$ – The process ID of the current script or application or bash shell.
  • $USER – The current user name.
  • $HOSTNAME – The hostname of the system.
  • $SECONDS – The number of seconds since the script was started.
  • $RANDOM – Returns random number for every call.
  • $LINENO – Returns the current line number in the Bash script.

Read User Input and Assign To Variable

Bash variables value is generally set via the bash terminal or script. But in some cases, we may need to set the value of the variable interactively reading the user input. The input() method can be used to get user input interactively.

name = input("What is your name?")

echo "Your name is $name"

Export Variable

Bash stores variables inside its processes and every new bash shell or process is a new environment that is isolated from other bash shells by default. But we can export variables inside a bash shell to make them available for other bash shells currently running. The export command is used to export a variable. In the following example, we export the variable name age which will be available for the other bash shells currently running.

age = 10

export age

Leave a Comment