- How to use Variables in Bash Programming
- Using variable from command line or terminal
- Example-1: Declaring and reading string data using variable
- Example-2: Combining two string variables
- Example-3: Concatenating strings with variables
- Example-4: Declaring and reading numeric data using variables
- Example-5: Doing arithmetic operation using bc command
- Using variables in bash file
- Example-6: Creating simple bash script
- Example-7: Using global and local variables
- Example-8: Using array variable
- About the author
- Fahmida Yesmin
- How do I set an environment variable on the command line and have it appear in commands?
How to use Variables in Bash Programming
Variables work as temporary storage for any programming language. The coder needs to have a clear concept of using different variables in the code. Variables are used to store specific data. The most commonly used data type of variables are integer, string, float, double and Boolean. The data type of any variable has to be defined at the time of variable declaration for strongly type programming languages. But BASH is a weakly typed programming language that does not require to define any data type at the time of variable declaration. So when any numeric value assigns to a variable then it will work as integer and when any text value assigns to a variable then it is string. BASH variables can be used from terminal or on any BASH file. The use of different types of BASH variables are described in this tutorial by using many examples.
Using variable from command line or terminal
You don’t have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use ‘$’ symbol before the variable name when you want to read data from the variable. You can set and get data from a variable from the terminal in the following way.
Example-1: Declaring and reading string data using variable
Run the following commands from the terminal.
Example-2: Combining two string variables
You don’t have to use any operator to combine two or more strings like other languages. Here, $var1 is used to store string value and $var2 is used to store a numeric value. Run the following commands from the terminal to combine two variables $var1 and $var2.
**Note: You can print the value of the variable without any quotation but if you use quotations then you have to use double quotations.
Example-3: Concatenating strings with variables
Double quotation can be used to read the value of the variable. In this example, single quotation is used on one echo statement and double quotation is used on another echo statement. Run the following commands from the terminal to check the output.
Example-4: Declaring and reading numeric data using variables
One of the major limitations of Bash programming is that it can’t perform arithmetic operations like other programming languages. Numeric values are taken as strings in BASH. So no arithmetic operation can be done by normal expression and it just combines the numeric values. If you write the expression with double first bracket then the arithmetic operation works properly. Run the following commands from the terminal.
Example-5: Doing arithmetic operation using bc command
bc command is another way to do arithmetic operation in BASH. Run the following commands from the terminal. When you use bc command only for doing any arithmetic operation then fractional parts are omitted from the result. You have to use -l option with bc command to get the result with fractional value.
Using variables in bash file
You can define variable in bash file by the same way which are mentioned in above examples. You have to create file with .sh or .bash extension to run bash script.
Example-6: Creating simple bash script
Copy the following code in a text editor and save the file with bash extension. In this script, one string and one numeric variables are declared.
str = «Learn BASH Programming»
#print string value
echo $str
#subtract 20 from numeric variable
( ( result = $num — 20 ) )
#print numeric value
echo $result
Example-7: Using global and local variables
In the following script, one global variable n and two local variables n and m are used.
When the function addition() is called then the value of the local variable n is taken for calculation but global variable n remains unchanged.
#!/bin/bash
n = 5
function addition ( )
{
local n = 6
local m = 4
( ( n =n+m ) )
echo $n
Example-8: Using array variable
Array variable is used to store a list of data. The following example shows how you use of array variable in bash script. The elements of any array are separated by space in BASH. Here, an array of 6 elements is declared. There is no built-in function or property to count the total elements of the array. # with * is used to count total elements. All elements are indicated by *. For loop is used here to iterate the array values. Reading array values and array values with key are shown in the next part of this script.
myarr = ( HTML JavaScript PHP jQuery AngularJS CodeIgniter )
#Count total number of elements of the array
total = $
echo «Total elements: $total «
#Print each element value of the array
echo «Array values :»
for val in $
do
printf » %s \n » $val
done
#Print each element value of the array with key
echo «Array values with key:»
for key in $
do
printf «%4d: %s \n » $key $
done
To use BASH variables properly you need a clear concept on the declaration and use of variables. This tutorial will help you to get a clear idea on BASH variables. After exercising the above examples properly you will be able to use variables more efficiently in your bash scripts.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
How do I set an environment variable on the command line and have it appear in commands?
export will make the variable appear in the environment of subsequently executed commands (for on how this works in bash see help export ). If you only need the variable to appear in the environment of one command, use what you have tried, i.e.:
The shell syntax describes this as being functionally equivalent to:
export TEST=foo your-application unset TEST
Interesting part is, that the export command switches the export flag for the variable name. Thus if you do:
unset TEST export TEST TEST="foo"
TEST will be exported even though it was not defined at the time when it was exported. However further unset should remove the export attribute from it.
The same reason — the shell expands the $TEST before the command line is executed. Once the echo is running (also note that echo will usually translate to the shell built-in command and not to /bin/echo ) it sees the variable set in its environment. However, echo $TEST doesn’t tell echo to output the contents of variable TEST from its environment. It tells the shell to run echo with argument being whatever currently is in the variable called TEST — and those are two very different things.
As I explained to you here: it’s because variables are expanded inside double quotes (e.g., «… $var …» ) but not inside single quotes (e.g., ‘… $var …’ ). Since echo «$var» is inside single quotes, that entire string gets passed to the new ( sh -c ) shell without being interpreted by the outer, interactive shell. … (Cont’d)
using two commands would work, but the reason why one simple command does not output foo IMO explained incorrectly, another answer is much better: unix.stackexchange.com/a/56454/266260: echo is usually a built-in and is not executed, var=value sh -c ‘echo «$var»‘ works as one would expect.
I suspect you want to have shell variables to have a limited scope, rather than environment variables. Environment variables are a list of strings passed to commands when they are executed.
You’re passing the var=value string to the environment that echo receives. However, echo doesn’t do anything with its environment list¹ and anyway in most shells, echo is built in and therefore not executed.
That would have been another matter. Here, we’re passing var=value to the sh command, and sh does happen to use its environment. Shells convert each of the variables they receive from their environment to a shell variable, so the var environment variable sh receives will be converted to a $var variable, and when it expands it in that echo command line, that will become echo value . Because the environment is by default inherited, echo will also receive var=value in its environment (or would if it were executed), but again, echo doesn’t care about the environment.
Now, if as I suspect, what you want is to limit the scope of shell variables, there are several possible approaches.
Portably (Bourne and POSIX):
(var=value; echo "1: $var"); echo "2: $var"
The (. ) above starts a sub-shell (a new shell process in most shells), so any variable declared there will only affect that sub-shell, so I’d expect the code above to output «1: value» and «2: » or «2: whatever-var-was-set-to-before».
With most Bourne-like shells (see List of shells that support `local` keyword for defining local variables), you can use functions and the «local» builtin:
With zsh, you can use inline functions:
With bash and zsh (but not ash, pdksh or AT&T ksh), this trick also works:
var=value eval 'echo "1: $var"'; echo "2: $var"
A variant that works in a few more shells ( dash , mksh , yash ) but not zsh (unless in sh / ksh emulation):
var=value command eval 'echo "1: $var"'; echo "2: $var"
(using command in front of a special builtin (here eval ) in POSIX shells removes their specialness (here that variables assignments in front of them remain in effect after they have returned))
¹ Stricktly speaking, that’s not completely true. Several implementations will care about the localisation environment variables ( LANG , LOCPATH , LC_* . ), the GNU implementation cares about the POSIXLY_CORRECT environment variable (compare env echo —version with POSIXLY_CORRECT=1 env echo —version on a GNU system).