In this post, we'll discuss how to define, use and set variables in shell script.

We will cover different examples like shell variable in loop, printing variables, string variable, set variable to output. Most of the examples work on Bash scripts.

define shell variables

To define shell variables we use the following syntax:

my_variable=some_value

Shell variable examples:

n=10 #number
name="Linux" #string
OS="Linux Mint"
Tip:

Symbol # indicates inline comment in bash

access variable values

To access variable values use this syntax - prepend $ in front of the variable name:

$my_variable

Example of accessing variable value in Bash:

n=10
echo $n

The result is 10.

shell variable names

There are different conventions and styles for naming shell variables. Example of shell naming conventions:

  • MY_VARIABLE - uppercase with underscore
  • my_variable_name - lowercase with underscore ( snake case)
  • myVariable - camel case
  • MyVariable - Pascal case

Usually environment variables or OS shell variables use capital letters. To prevent collision you may use lowercase.

Tip:

Once you select one just stick with it. Consistency and clearness is more important in this case.

On the other hand variable names can not start with: digit or contain spaces. Variable names can only contain underscores and alpha-numeric characters.

shell variable types

Depending on the context we can divide variable in different types like:

System / User variables

There are two shell variable types based on this criteria:

  • User defined
  • System defined

environment or local

We can divide variables into several groups like:

  • local - usually it has script scope
  • environment - these variables helps programs to work correctly
  • shell

You can read more about them on this great Linux resource: Windows and Linux variable equivalents

data types

Shell variables don't have data types. But there is a slight difference on how we define them and how they behave.

Example of definition of number and string variable in bash:

var1=10
echo $var1 + $var 1
echo $(($var1 + $var1))

var2=value
echo $var2 + $var2
echo $(($var2 + $var2))

When we try to sum (add) two variables in bash we can see that:

10 + 10
20
value + value
0

That on numeric variables we can apply arithmetic operations.

Readonly variables

Shell variables can be defined as read-only by word:

readonly PI=3.14

command not found

In shell or Bash we might get issues like:

  • "variable not found"
  • "command not found"

The reason is incorrect usage and evaluation of shell variables. The code below demonstrate the error:

var1=five
$($var1 + 5)

This results into:

five: not found

In some shells we might get error command not found

Another example of shell error: command not found is raised from this code:

$((((RANDOM + RANDOM) % 63001) + 2000))

check if variable is defined

We'll create an example of how to check if a shell variable is defined. Next, we'll see multiple useful examples:

This example shows how to check if shell variable is set:

var=1
[ -n "$var" ] && echo "test1: var is set and not empty"
[ -z "$var" ] && echo "test2: var is unset or empty"
[ "${var+x}" = "x" ] && echo "test3: var is set"
[ -n "${var+x}" ] && echo "test4: var is set"
[ -z "${var+x}" ] && echo "test5: var is unset"
[ -z "${var-x}" ] && echo "test6: var is set and empty"

result:

test1: var is set and not empty
test2: var is set
test3: var is set

While running the tests when variable is not set give us:

test5: var is unset or empty
test6: var is unset

Tests above help to find if the bash variable is set or unset, empty or with value.

define shell variable in loop

To define shell variables we can use the following syntax:

max=5
for num in $(seq 1 $max); do
	echo $num;
done

we get:

1
2
3
4
5

In this example we use the outside variable in the loop. We define the variable num and use it in the loop.

shell variable in string

We can use variables in strings. To assign a variable to a string in shell script we use $.

Example of assigning a variable to a string in shell script:

#!/bin/bash

domain='https://en.wikipedia.org/'
path='wiki/Linux'
base_url="$domain$path"
echo $base_url

append to string variable

To concatenate string variables in shell or bash we can use ${} and place the variable inside new string:

#!/bin/bash

foo="Hello"
bar="${foo} World!"
echo "${bar}"

or we can append to variable by += which works only in bash:

#!/bin/bash

foo="Hello"
foo+=" World!"
echo "${foo}"

So you need to run with: ./test.sh. If you try to run the script by: sh test.sh you will get bash error: 'command not found':

test.sh: 4: foo+= World!: not found

shell variables cheat sheet

There is great cheat sheet for shell and shell variables. Extraction from this cheat sheet for variables is placed below:

varname=value                # defines a variable
varname=value command        # defines a variable to be in the environment of a particular subprocess
echo $varname                # checks a variable's value
echo $$                      # prints process ID of the current shell
echo $!                      # prints process ID of the most recently invoked background job
echo $?                      # displays the exit status of the last command
read <varname>               # reads a string from the input and assigns it to a variable
read -p "prompt" <varname>   # same as above but outputs a prompt to ask user for value 
column -t <filename>         # display info in pretty columns (often used with pipe)
let <varname> = <equation>   # performs mathematical calculation using operators like +, -, *, /, %
export VARNAME=value         # defines an environment variable (will be available in subprocesses)
export -f  <funcname>        # Exports function 'funcname'
export var1="var1 value"     # Export and assign in the same statement
export <varname>             # Copy Bash variable 
declare -x <varname>         # Copy Bash variable 

array[0]=valA                # how to define an array
array[1]=valB
array[2]=valC
array=([2]=valC [0]=valA [1]=valB)  # another way
array=(valA valB valC)              # and another

You can find the link in the final section.

summary

In this post we covered questions and topics like:

  • How to set variables in shell script?
  • variables in shell script examples
  • shell script variable in string
  • user defined variables in shell script
  • types of variables in linux
  • shell variables example
  • shell variable types
  • declare variable in shell script
  • shell variable in loop

So hopefully you will know more about shell and bash variables.

resources