raspberry pi

Variables in Bash Programming Explained with Example Codes

Variables in Bash Programming:

Variables are assigned using the = operator. It is allowed between the Variable names and the sign = no space! var = abc is syntactic wrong and not working! To read out variables you have to use the Put a $ sign in front of the name. The easiest way to show the contents of a shell variable is with echo to:

var = abc

echo $ var # output abc

Basically, all bash variables contain strings. var = abc is only an abbreviation for var = ‘abc’. The apostrophes are essential if the character string to be saved contains spaces or special characters. Several character strings can be directly strung together during the assignment will. In the following example a new character string is assigned to the variable, those from their old content, the character string and again the original Content consists of:

a = 3

a = $ a 'xxx' $ a

echo $ a # issue 3 xxx3

If variables contain integers, you can count on them. You have to however, keep to the syntax $ [expression], which takes getting used to. The bash can only calculate with whole numbers and knows no floating point numbers:

echo $ [2 + 3] # output 5

a = 3

b = 4

c = $ [$ a / $ b +1]

echo $ c # output 1 (3/4 results in 0, +1)

Variables and $ expressions in strings with double apostrophes are evaluated. This does not apply to strings in single apostrophes:

echo "a = $ a b = $ b c = $ c $ [$ a + $ b + $ c]" # output a = 3 b = 4 c = 1 8

echo 'a = $ a b = $ b c = $ c $ [$ a + $ b + $ c]' # output a = $ a ...

Read variables with read

With read you can make user input. Usually you give this first echo out a short text in which you inform the user what input you expect, e.g. y / n, a numeric value etc. The -n option is useful so that the entry is immediately after the echo text and not on the next line. When executing the subsequent readCommands, bash waits until the user enters a line and this ends with (pressing enter button).

In the following sample program, the while loop is executed until the Character string in the variable is no longer empty. After entering through readline the entire content of the variable is deleted via parameter substitution, if any character in it except a digit, a minus sign or a space occurs. This control is not perfect because it has strings like “12-34-5” and “12 34” accepted, but quite effective. Information on Parameter substitution with $ {var ## muster}, for making comparisons and to form loops follow on the next pages.

#! / bin / bash

# read in a numeric value

a = # delete a

while [-z "$ a"]; do

echo -n "Please enter a number:"

read a

a = $ {a ## * [^ 0 -9, '', -] *} # Eliminate strings that

# any characters except 0-9, the

# Minus sign and the space

# contain

if [-z "$ a"]; then

echo "Invalid entry, please repeat entry"



echo $a

Environment variables in Bash Programming

Bash also knows so-called environment variables. This is on the one hand all predefined variables that are already known in the terminal window and which you can determine with the printenv command (see Table 1).

On the other hand, you can use export var [= value] to add a variable to the environment variable yourself do. As a result, this variable is used in all commands or Scripts can be read out that you call from your program.

Table 1: Important environment variables in bash programming

variable Importance
HOME the home directory
LANG Localization settings, i.e. language and character set
PATH Directories in which programs are searched for
PS1 Content / appearance of the command prompt
PWD the current directory
USER the login name of the active user


Predefined  variables in bash programming

bash scripts can access some predefined variables. These variables cannot be changed by assignments, but only read – for example, to process the parameters passed to a script. The name of Variables are formed by various special characters (see table2). The abbreviation PID stands for Process ID, i.e. for the internal process number.

Table 2: Predefined bash variables

variable Importance
$? Return value of the last command
$! PID of the background process started last
$$ PID of the current shell
$0 Filename of the executed script
$# Number of parameters
$1 to $9 Parameters 1 to 9
$ * or $ @ Totality of all transferred parameters


In addition to simple variables, bash also knows fields (arrays). These are data structures for storing multiple values. Common arrays use whole numbers as an index. Note that it differs from many other programming languages Syntax $ {field [n]} for access to the nth element.

x = () # Definition of an empty array

x [0] = 'a' # Assign array elements

x [1] = 'b'

x [2] = 'c'

x = ('a' 'b' 'c') # Short notation for the 4 lines above

echo $ {x [1]} # read an array element

echo $ {x [@]} # read all array elements

Bash also knows associative arrays. To do this, you must explicitly use the field variable declare -a as associative!

declare -A y # Definition of an empty associative array

y [abc] = 123 # Assign element of an associative array

y [efg] = xxx

y = ([abc] = 123 [efg] = xxx) # shorthand

echo $ {y [abc]} # read an array element

With mapfile you can transfer an entire text file line by line into the elements of a ordinary arrays:

mapfile z <textfile

Parameter substitution

Bash lacks the functions common in most other programming languages or methods for processing character strings, so to i.e. the first three Characters to read or the last five. Bash knows this under the term Parameter substitution have some very powerful mechanisms for converting information to extract from strings that are stored in variables:

  • $ {var: -default}: If the variable is empty, the construction returns the default setting

as a result, otherwise the content of the variable. The variable won’t changed.

var =

echo $ {var: - abc} # output abc

var = 123

echo $ {var: - abc} # output 123
  • $ {var: = default}: As above, but the content of the variable is changed at the same time, if this was previously empty.
  • $ {var: + new}: If the variable is empty, it remains empty. If the variable is against is already occupied, the previous content will be replaced by a new setting. The Construction supplies the new content of the variable.
  • $ {var:? error message}: If the variable is empty, the variable name and the error message is displayed and the shell program is then exited. Otherwise the construction supplies the content of the variable.
  • $ {# var}: returns the number of characters stored in the variable as a result or 0 if the variable is empty. The variable is not changed.
x = 'abcde'

echo $ {# x} # Issue 5
  • $ {var \ #muster}: compares the beginning of the variable with the specified pattern. If the pattern is recognized, the construction supplies the content of the variable minus the shortest possible text that matches the search pattern. If the pattern is not found, however, the entire content of the variable is used returned. In the search pattern, the Wildcards are used, i.e. *,? and [abc]. The variable is in not changed in any case.
dat = / home / pi / pictures / img123 .png

echo $ {dat # * /} # output home / pi / pictures / img123. png

echo $ {dat # *.} # output png
  • $ {var ## pattern}: as above, but now the largest possible character string, which corresponds to the pattern eliminates:
echo $ {dat # # * /} # output img123. Png

echo $ {dat # # *.} # output png
  • $ {var% sample}: like $ {var # sample}, but the sample comparison will now take place on End of variable content. It will be the shortest possible string from the end of the variables eliminated. The variable itself remains unchanged.
echo $ {dat% / *} # output / home / pi / pictures

echo $ {dat%. *} # output / home / pi / pictures / img123
  • $ {var %% sample}: as above, but now the largest possible string is eliminated:
echo $ {dat %% / *} # no output (empty string)

echo $ {dat %%. *} # output / home / pi / pictures / img123
  • $ {var / find / replace}: replaces the first occurrence of the pattern find with replace:
x = 'abcdeab12ab'

echo $ {x / ab / xy} # output xycdeaab12ab
  • $ {! var} returns the content of the variable whose name is in the string is included:
abc = 123

efg = 'abc'

echo $ {! efg} # Issue 123

Form strings or lists

If you want to join several strings together, enter the strings or the corresponding variables just one after the other:

a = 123

b = efg

echo $ a $ b # output 123 efg

With the syntax {a, b, c} or {n1..n2} or {character1..character2} you can create lists form, for example to then process them in a loop. The lists are only output in the following examples:

echo {1, 3, 5} # output 1 3 5

echo {1..6} # output 1 2 3 4 5 6

echo {a .. g} # output a b c d e f g

If several {} expressions are strung together, bash creates all possible ones Combinations. The bash nomenclature calls this {} syntax Brace Expansion.

echo {ab, cd} {1, 2, 3} # output ab1 ab2 ab3 cd1 cd2 cd3

echo {a .. d} {4..7} # output a4 a5 a6 a7 b4 b5 b6 b7

# c4 c5 c6 c7 d4 d5 d6 d7


Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button