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:

allpcb circuit


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:

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:

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



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.


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


Fields

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.

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

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: = 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.

  • $ {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.

  • $ {var ## pattern}: as above, but now the largest possible character string, which corresponds to the pattern eliminates:

  • $ {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.

  • $ {var %% sample}: as above, but now the largest possible string is eliminated:

  • $ {var / find / replace}: replaces the first occurrence of the pattern find with replace:

  • $ {! var} returns the content of the variable whose name is in the string is included:



Form strings or lists

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

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:

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

 

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...

Related Articles

Leave a Reply

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

Back to top button