How to work with variables in bash

A guide to setting up and executing Bash scripts. You will also learn the most essential aspects of Bash syntax.

Bash scripting is an extremely useful and powerful part of system administration and development. It might seem extremely scary the first time you do it, but hopefully this guide will help ease the fear.

Bash is a Unix shell, which is a command line interface (CLI) for interacting with an operating system (OS). Any command that you can run from the command line can be used in a bash script. Scripts are used to run a series of commands.

Bash is available by default on Linux and macOS operating systems.

This is not meant to be an extensive guide to bash scripting, but just a straightforward guide to getting started with making your first script, and learning some basic bash syntax.

Note: Newer macOS installations (from Catalina) come installed with zsh (Z shell) as the new default, but everything in this article will still be applicable.

  • A basic command line knowledge is required. Everything you need to know to get started can be found in my How to Use the Command Line article.

This guide was created on macOS, and will be using /Users/you as the default user directory for all examples. However, the concepts here will apply to any Unix-like operating system, including macOS and various Linux distributions.

In this tutorial, we’re going to:

  • Create a bash script
  • Learn about:

Create Your First Script

Making a bash script is a lot simpler than you might think.

Create a file called hello-world , using the touch command.

Edit the file with the program of your choice. Within the file, print a string that says “Hello, world!’ using echo .

Now from the command line, run the script using the bash interpreter:

You’ll see the script has run successfully from the output.

That’s it, you’ve created your first script!

So far, you’ve learned how to run a script from the command line prefixed with the bash interpreter. However, if you want to run the script by name alone, it won’t work. Try to run the file simply by typing the name of the file and pressing enter. Note that we’re prefixing the file with ./ , which means a file in the current directory.

In order to run a file directly, we’ll need to change the permissions to allow the script to be executable for the user. chmod is a command that changes permissions on a file, and +x will add execute rights to the script.

In order to interpret the file as an executable, you’ll also have to add the shebang ( #! ) at the top of the script. In Unix-like systems, a text file with a shebang is interpreted as an executable file. You can confirm where the bash interpreter is located with which bash.

We’ll add #!/bin/bash to the top of the script.

Note: You may also see #!/usr/bin/env bash instead, which can be used if you don’t know the exact path for bash.

Now you can run hello-world directly.

Note: In order to run a bash script without specifying the directory (using ./ , for example) you would have to add the directory of the script to the PATH by running export PATH=$PATH:/path/to/script/directory . However, this is generally not necessary for personal scripts.

A simple string in Bash does not require double quotes – you can write it directly.

A single or double quote will expect a closing match, so in order to use one in such a string, you would need to escape the quote.

However, if you want to use a single or double quote in a string without escaping characters, you can do so by wrapping your string in quotes.

With the -e flag, bash will interpret strings with backslash-escaped characters, such as \n for newline. This also requires a quoted string.

Double quoted strings are also important for use with variables, as we’ll see in the next section.

A variable is declared without a dollar sign ( $ ), but has one when invoked. Let’s edit our hello-world example to use a variable for the entity being greeted, which is World .

Note that who = “World” with a space between the assignment is not valid – there must not be a space between variable and value.

Double quoted strings are required for interpolating variables. Within a single quoted string, the dollar sign would be interpreted literally

Another way you might see variables written is surrounded by curly brackets along with the dollar sign, which is known as parameter expansion.

This syntax is necessary for anything more complex you might do with a variable, such as getting one item from an array.

If you would like to use the output of a shell execution within a string, you can do so with a dollar sign followed by parentheses. ( $() ). For example the whoami command will print out your current user. To use it within a string, wrap whoami in the shell execution syntax.

We declared a variable in the last example, but we can also have the user set the value of a variable dynamically. For example, instead of just having the script say Hello, World! , we can make it ask for the name of the person calling the script, then output that name. We’ll do this using the read command.

Operators are slightly different in bash than what you might be used to.

In order to compare numbers, you will use the operators in the number comparison column, such as -lt for less than.

In order to compare strings, you will use the operators in the string comparison column, such as < for less than.

This is the opposite of what you might expect, but it’s the way it works in bash.

Number Comparison String Comparison Description
-eq == Equal
-ne != Not equal
-gt > Greater than
-ge >= Greater than or equal
-lt < Less than
-le <= Less than or equal

You can also use -z to test for emptiness on a string.

if statements use the if , then , else , and fi keywords. The condition goes in square brackets.

Bash uses for , while , and until loops. In this example, I’ll use the for. in loop to get all the files in a directory and list them.

An array in bash is defined inside parentheses. There are no commas between the items of the array.

To access an item from an array, you’ll use square brackets ( [] ). Arrays are 0-indexed in bash. It is also necessary to use the paramter expansion syntax.

I hope this article has been helpful for you to get started with bash scripting. The concept of having a script that has complete access to anything on my computer was initially a frightening thought for me, but once I got accustomed to it I learned how useful and efficient it can be.

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.

Output:

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.

Output:

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

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.

Output:

How to work with variables in bash

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.

Output:

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

Output:

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

Output:

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 = $ <#myarr[*]>
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

Output:

How to work with variables in bash

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.

By Alokananda Ghoshal

How to work with variables in bash

Introduction to Bash Script Variables

For people who have been into programming, variables are a concept that is widely used irrespective of the type of programming type or language. But in case this is your firsthand on understanding variables, we would try to give an analogous circumstance to get a feeling of variable and then get into the technical aspect of variable. In a big retail store, we have a temporary store where things might be stored for a temporary purpose, and when the items in the front end are over, the ones from a temporary store are loaded into front end. Similar to that, a variable is also a temporary store for storing a piece of information. These variables are pretty handy when it comes to managing and control actions in a programming scenario. In bash script itself, these variables go a long way in allowing developers to manage and control the flow or the outcome of an algorithm in the coding world! Not only this since they are so easily adaptable to circumstances, one can land up into grave trouble if the understanding is not proper in terms of working of variables. Hence, in this article, we will make sure that there is a proper understanding of even the minute things to help you get the best in just one article!

How do Bash Script Variables work?

Now let us answer the very basic question first, how do a variable work? To answer this, we would need to first understand the 2 actions that can be performed on a variable and they are:

Web development, programming languages, Software testing & others

  • Variable value setting.
  • Variable value reading.

We would slowly see the following actions in place below, but for now let us come back to understand how the variable work. With the 2 actions mentioned above, a variable itself can be set and assigned a value, which essentially means that the variable is now containing a value. Now this variable will be more useful when the value assigned to the variable can be used in any operation. This is where variable value reading comes to play!

Feature

Now let us look at some feature sets which is brought to the table by variables.

  • Command-line arguments: As the name suggests, these are the arguments sent through the command line. Now the bash will try to interpret the arguments sent and assign each of them to a variable. They are referenced in a special way, i.e. using $ for example, $1 for the first argument, $9 for the 9 th argument, and so on!
  • $USER: This is again a reserved variable, which is assigned with a value of username of the user to run the script.
  • $RANDOM: This is another reserved variable, which returns a new random variable every time it is referenced to.
  • Usage of Quotes: In case a developer wants to assign a value, and this value has spaces in it, we would use quotes at the start and end of the variable to make it as a single value for assigning. The quotes can be single or double!
  • Command Substitution: In some special cases we would like to execute a command on the fly and assign the result of the command to a variable. It is done easily in bash by just preceding the command with $ sign and putting the entire command within brackets!

Few pointers to be remembered while dealing with variables:

  • When we read a variable for its value, we would use $ sign to reference that the name given is a variable whose value we are trying to access.
  • While value is set for a variable, we don’t use the $
  • As a standardized coding practice, camel-casing is the most preferred naming convention for variable names.
  • There is no clear restriction on the placement of a variable.

Examples to Implement Bash Script Variables

From the above theoretical concepts we discovered some features which can be utilized effectively as a bash script argument and now in this section we will discuss an example where we would showcase the above features’ actual working right in front of your eyes giving you enough confidence to try them in real-life problem-solving.

Code:

#!/bin/bash
echo “**We would look at the arguments sent by command line:**”
echo “Argument number 1: $1”
echo “Argument number 2: $2”
echo ” ”
echo “The name of the user running the shell is: $USER”
echo “The first random number generated is: $RANDOM”
echo “The second random number generated is: $RANDOM”
var1=”World of EduCBA”
echo ” ”
echo “The varriable: $var1 has spaces but still considered as single variable: No Error”
echo “Similar to the * command @ command also prints all the values passed in the script as: [email protected]
echo ” ”
echo “Understanding how command is substituted for a variable”
var2=$( ls | wc -l )
echo “We have $var2 entries in the current working directory!”

Output:

How to work with variables in bash

Conclusion

So now we can confidently say that we have in-depth covered the workings of bash script variables and this working architecture of variables is the single most important tool for bash script to help these scripts enjoy the flavor of success they currently enjoy! Some other topics are there as well like exporting of variables, but these are not widely used in the industry and hence have kept them for some other placeholder to talk about!.

Recommended Articles

This is a guide to Bash Script Variables. Here we discuss an introduction to Bash Script Variables, how does it work with programming examples. You can also go through our other related articles to learn more –

When your bash scripts get bigger and bigger, things can get very messy!

You may find yourself rewriting the same pieces of code again and again in different parts of your bash scripts.

Luckily, you can avoid rewriting code by using functions in bash which will make your scripts more organized and readable.

In this tutorial, you will learn to create functions, return function values, and pass function arguments in bash shell scripts.

Furthermore, you will learn how variables scope work and how to define recursive functions.

Creating functions in bash

There are two different syntaxes for declaring bash functions. The following syntax is the most common used way of creating bash functions:

The second less commonly used of creating bash functions starts with the reserved work function followed by the function name as follows:

Now there are a couple of things you should be well aware of when working with functions:

  • A function will never run/execute unless you invoke/call the function.
  • The function definition must precede any calls to the function.

Anytime you want a function to run, you just need to call it! A function call is done by simply referencing the function name.

Take a look at the following fun.sh bash script:

I defined a function named hello that simply echo’s the line “Hello World” to the terminal. Notice that I did three hello function calls and so if you run the script, you will see the “Hello World” line printed three times on the screen:

Returning function values in bash

In many programming languages, functions do return a value when called; however, this is not the case with bash as bash functions do not return values.

When a bash function finishes executing, it returns the exit status of the last command executed captured in the $? variable. Zero indicates successful execution or a non-zero positive integer (1-255) to indicate failure.

You can use a return statement to alter the function’s exit status. For example, take a look at the following error.sh script:

If you run the error.sh bash script, you might be surprised of the output:

Without the return 0 statement, the error function would have never returned a non-zero exit status as blabla is results in a command not found error.

So as you can see, even though bash functions do not return values, I made a workaround by altering function exit statuses.

You should also be aware that a return statement immediately terminates a function.

Passing arguments to bash function

You can pass arguments to a function just like you can pass arguments to a bash script. You just include the arguments when you do the function call.

To demonstrate, let’s take a look at the following iseven.sh bash script:

The iseven() function tests whether a number is even or odd. I did four function calls to iseven(). For each function call, I supplied one number which is the first augment to the iseven() function and is referenced by the $1 variable in the function definition.

Let’s run the iseven.sh bash script to make sure it works:

You should also be well aware that bash function arguments and bash script arguments are two different things. To contrast the difference, take a look at the following funarg.sh bash script:

Run the script with a couple of arguments and observe the result:

As you can see, even though you used the same variables $1 and $2 to refer to both the script arguments and the function arguments, they produce different results when called from within a function.

Local and global variables in bash functions

Bash variables can either have a global or local scope. You can access a global variable anywhere in a bash script regardless of the scope. On the contrary, a local variable can only be accessed from within their function definition.

To demonstrate, take a look at the following scope.sh bash script:

I first defined two global variables v1 and v2. Then inside myfun() definition, I used the local keyword to define a local variable v1 and modified the global variable v2. Note that you can use the same variable name for local variables in different functions.

Now let’s run the script:

From the script output, you can conclude the following:

  • A Local variable that have the same name as a global variable will take precedence over global variables inside a function body.
  • You can change a global variable from within a function.

Recursive functions

A recursive function is a function that calls itself! Recursive functions come in handy when you attempt to solve a programming problem that can be broken down to smaller subproblems.

The factorial function is a classic example of a recursive function. Take a look at the following factorial.sh bash script:

Any recursive function must begin with a base case which is necessarily to end the chain of recursive function calls. In the factorial() function, the base case is defined as follows:

Now derive the recursive case for the factorial function. To calculate the factorial of a number n where n is a positive number greater than one, you can multiply n by the factorial of n-1:

Let’s use the above equation to write this recursive case:

Now run the script and make sure to get the correct results:

As an additional exercise, try to write a recursive function to calculate the nth Fibonacci number. First, try to come up with the base case and then the recursive case; you got this!

Awesome! This brings us to the end of this week’s tutorial. I hope you have enjoyed creating functions in bash! Stay tuned for next week as you will apply everything you have learned so far to write effective bash scripts that automate boring administrative tasks.

I want to call a settings file for a variable, how can I do this in bash?

So the settings file will define the variables (eg: CONFIG.FILE) :

And the script will use those variables in it

How can I get bash to do something like that? Will I have to use awk/sed etc.

How to work with variables in bash

9 Answers 9

The short answer

Use the source command.

An example using source

config.sh

script.sh

Note that the output from sh ./script.sh in this example is:

This is because the source command actually runs the program. Everything in config.sh is executed.

Another way

You could use the built-in export command and getting and setting “environment variables” can also accomplish this.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

To set them, say:

at the command line. All scripts will be able to access this value.

even shorter using the dot:

Use the source command to import other scripts:

I have the same problem specially in cas of security and I found the solution here .

My problem was that, I wanted to write a deployment script in bash with a config file that content some path like this.

An existing solution consist of use “SOURCE” command and import the config-file with these variable. ‘SOURCE path/to/file’ But this solution have some security problem, because the sourced file can contain anything a Bash script can. That creates security issues. A malicicios person can “execute” arbitrary code when your script is sourcing its config file.

Imagine something like this:

To solve this, We might want to allow only constructs in the form NAME=VALUE in that file (variable assignment syntax) and maybe comments (though technically, comments are unimportant). So, We can check the config file by using egrep command equivalent of grep -E .

This is how I have solve the issue.

in Bash, to source some command’s output, instead of a file:

Usually I go about parsing instead of sourcing, to avoid complexities of certain artifacts in my file. It also offers me ways to specially handle quotes and other things. My main aim is to keep whatever comes after the ‘=’ as a literal, even the double quotes and spaces.

Note the little trick I had to do to consider my quoted text as a single parameter with space to my cntpars function. There was one extra level of evaluation required. If I wouldn’t do this, as in Option 2, I would have passed 2 parameters as follows:

  • “value
  • content”

Double quoting during command execution causes the double quotes from the parameter file to be kept. Hence the 3rd Option also fails.

The other option would be of course to just simply not provide variables in double quotes, as in Option 4, and then just to make sure that you quote them when needed.

Just something to keep in mind.

Another thing I like to do is to do a real-time lookup, avoiding the use of environment variables:

In every programming language variables plays an important role , in Linux shell scripting we are using two types of variables : System Defined Variables & User Defined Variables.

A variable in a shell script is a means of referencing a numeric or character value. And unlike formal programming languages, a shell script doesn’t require you to declare a type for your variables

In this article we will discuss variables, its types and how to set & use variables in shell scripting.

System Defined Variables :

These are the variables which are created and maintained by Operating System(Linux) itself. Generally these variables are defined in CAPITAL LETTERS. We can see these variables by using the command “$ set“. Some of the system defined variables are given below :

How to work with variables in bash

To Print the value of above variables, use echo command as shown below :

# echo $HOME
# echo $USERNAME

We can tap into these environment variables from within your scripts by using the environment variable’s name preceded by a dollar sign. This is demonstrated in the following script:

#!/bin/bash
# display user information from the system.
echo “User info for userid: $USER”
echo UID: $UID
echo HOME: $HOME

Notice that the environment variables in the echo commands are replaced by their current values when the script is run. Also notice that we were able to place the $USER system variable within the double quotation marks in the first string, and the shell script was still able to figure out what we meant. There is a drawback to using this method, however. Look at what happens in this example:

$ echo “The cost of the item is $15”
The cost of the item is 5

That is obviously not what was intended. Whenever the script sees a dollar sign within quotes, it assumes you’re referencing a variable. In this example the script attempted to display the variable $1 (which was not defined), and then the number 5. To display an actual dollar sign, you must precede it with a backslash character:

$ echo “The cost of the item is \$15”
The cost of the item is $15

That’s better. The backslash allowed the shell script to interpret the dollar sign as an actual dollar sign, and not a variable.

User Defined Variables:

These variables are defined by users. A shell script allows us to set and use our own variables within the script. Setting variables allows you to temporarily store data and use it throughout the script, making the shell script more like a real computer program.

User variables can be any text string of up to 20 letters, digits, or an underscore character. User variables are case sensitive, so the variable Var1 is different from the variable var1. This little rule often gets novice script programmers in trouble.

Values are assigned to user variables using an equal sign. No spaces can appear between the variable, the equal sign, and the value (another trouble spot for novices). Here are a few examples of assigning values to user variables:

var1=10
var2=-57
var3=testing
var4=“still more testing”

The shell script automatically determines the data type used for the variable value. Variables defined within the shell script maintain their values throughout the life of the shell script but are deleted when the shell script completes.

Just like system variables, user variables can be referenced using the dollar sign:

$ cat test3
#!/bin/bash
# testing variables
days=10
guest=”Katie”
echo “$guest checked in $days days ago”
days=5
guest=”Jessica”
echo “$guest checked in $days days ago”
$

Running the script produces the following output:
$ chmod u+x test3
$ ./test3
Katie checked in 10 days ago
Jessica checked in 5 days ago
$

Each time the variable is referenced, it produces the value currently assigned to it. It’s important to remember that when referencing a variable value you use the dollar sign, but when referencing the variable to assign a value to it, you do not use the dollar sign. Here’s an example of what I mean:

$ cat test4
#!/bin/bash
# assigning a variable value to another variable
value1=10
value2=$value1
echo The resulting value is $value2
$

When you use the value of the value1 variable in the assignment statement, you must still use the dollar sign. This code produces the following output:

$ chmod u+x test4
$ ./test4
The resulting value is 10
$

If you forget the dollar sign, and make the value2 assignment line look like:

value2=value1
you get the following output:
$ ./test4
The resulting value is value1
$

Without the dollar sign the shell interprets the variable name as a normal text string, which is most likely not what you wanted.

Use of Backtick symbol (`) in shell variables :

The backtick allows you to assign the output of a shell command to a variable. While this doesn’t seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters:

The shell runs the command within the backticks and assigns the output to the variable testing. Here’s an example of creating a variable using the output from a normal shell command:

$ cat test5
#!/bin/bash
# using the backtick character
testing=`date`
echo “The date and time are: ” $testing
$

The variable testing receives the output from the date command, and it is used in the echo statement to display it. Running the shell script produces the following output:

$ chmod u+x test5
$ ./test5
The date and time are: Mon Jan 31 20:23:25 EDT 2011

Note : In bash you can also use the alternative $(…) syntax in place of backtick (`),which has the advantage of being re-entrant.

Example : $ echo ” Today’s date & time is :” $(date)
Today’s date & time is : Sun Jul 27 16:26:56 IST 2014

Read Also : 9 ‘diff’ Command Examples in Linux

Read Also : 16 Echo Command Examples in Linux

I am doing a bash script to create a back-up of my mysql databases. Actually, I would like to delete the old ones.

So, I create my script with variable for maintability.

The whole script is actually working, the only one thing who does not work, is the delete of the old ones. I was thinking it would be the easiest part.

Anyway, here is my code, can someone telle me what’s wrong ? And the rm command returns me : rm: impossible de supprimer « /path/to/backup/files/*.gz »: Aucun fichier ou dossier de ce type Which means rm: impossible to delete « /path/to/backup/files/*.gz »: no files or directory of this type

But what is really strange, first is that I found the script in a tutorial

Two, that if I launch myself the “rm /path/to/backup/files/*.gz” in a shell command, this is working and deleting all the .gz files (as excpected)

How to work with variables in bash

3 Answers 3

shell command line tells the shell to execute /bin/rm with with two arguments: rm and /path/to/backup/files/*.gz .

The space, ” and $ are special characters in the shell language syntax. Space is used to delimit command arguments, ” is used to quote other special characters (not all, $ for instance is still special) like that * above, and $ is used for some expansions (like the $OUTPUT parameter expansion that you’re using here).

rm once started will try to remove that /path/to/backup/files/*.gz file. If that file doesn’t exist (as is the case for you), it will report an error.

Since * is not quoted this time, it triggers another special feature of the shell called globbing or filename generation or filename expansion. The shell tries to expand the word that contains that * character to the list of file names that match the pattern.

So if /path/to/backup/files contains a a.gz and b.gz files, the shell will actually call rm with 3 arguments: rm , /path/to/backup/files/a.gz and /path/to/backup/files/b.gz which looks more like what you want here.

Note that $OUTPUT itself still needs to be quoted as otherwise it could end up being split if it contains characters of $IFS or also be subject to globbing if it contained any wildcard characters (like that * above).

It’s also a good idea to get used to writing:

Here $OUTPUT happens to start with / , so it’s fine, but the day you change $OUTPUT to -foo- for instance, it will stop working as that -foo-/. would be taken by rm as options.

If the script is not meant to be interactive, you may want to add the -f option to rm . That will disable all user prompts, and remove the error if there’s no matching file (most shells, when a glob has no match, pass the pattern as-is to the application, and rm -f doesn’t complain when asked to remove a file that doesn’t exist in the first place).

I have tried to increment a numeric variable using both var=$var+1 and var=($var+1) without success. The variable is a number, though bash appears to be reading it as a string.

Bash version 4.2.45(1)-release (x86_64-pc-linux-gnu) on Ubuntu 13.10.

How to work with variables in bash

9 Answers 9

There is more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

Or you can use let :

How to work with variables in bash

Arithmetic in bash uses $((. )) syntax.

How to work with variables in bash

Thanks to Radu Rădeanu’s answer that provides the following ways to increment a variable in bash:

There are other ways too. For example, look in the other answers on this question.

Having so many options leads to these two questions:

  1. Is there a performance difference between them?
  2. If so which, which performs best?

Incremental performance test code:

Results:

Conclusion:

It seems bash is fastest at performing i+=1 when $i is declared as an integer. let statements seem particularly slow, and expr is by far the slowest because it is not a built into bash.

There’s also this:

Take careful note of the spaces and also ` is not

While Radu’s answers, and the comments, are exhaustive and very helpful, they are bash-specific. I know you did specifically ask about bash, but I thought I’d pipe in since I found this question when I was looking to do the same thing using sh in busybox under uCLinux. This portable beyond bash.

How to work with variables in bash

If you declare $var as an integer, then what you tried the first time will actually work:

How to work with variables in bash

There’s one method missing in all the answers – bc

bc is specified by POSIX standard, so should be present on all versions of Ubuntu and POSIX-compliant systems. The <<< redirection could be altered to echo "$VAR" | bc for portability, but since the question asks about bash - it's OK to just use <<< .

How to work with variables in bash

Bash allows you to map whole strings of text to single variables, simplifying its use and script writing. How do they work, and how can you use them? Let’s find out.

What’s a Variable?

Variables are easy-to-remember names that can contain different alphanumeric values. They’re useful because they allow the same function to be applied on different values, without having to rewrite a script/piece of code. They also make writing the script/piece of code easy, since instead of dealing with individual values, you can use the same name for all of them.

Also read: The Bash Special Characters You Should Know About

Realtime Variables

Bash allows the use of variables. You can create variables on the fly and reuse them during your current Bash session. They can assist your use of Bash in many different ways, and they’ll be gone after the current session ends.

For example, let’s say you’re visiting a bunch of sites. You could be doing research or scraping data. You could create the following variable:

How to work with variables in bash

After that, if you wanted to visit our site with Firefox, you can just type:

How to work with variables in bash

Much easier – and more readable. The $sitea variable would remain mapped to the site until you either changed its contents manually or the Bash session ended. And, of course, you can create more variables, such as siteb , sitec , and sited .

When setting up new variables, you can use any names you wish and store any alphanumeric strings inside them. Do keep in mind, though, that they’re case-sensitive by default. Thus, $sitea would not be the same as $SiteA . Also, note that you should use quotation marks when storing strings with special characters inside them (including spaces).

Variables in Scripts

Variables in Bash are more useful when writing scripts since they allow you to write a single script, which can then iterate through different strings or act on customized pieces of data. Let’s say that you’re writing a script that everyone could use on their computer, but each time would display a personalized greeting. Without variables, you’d have to write a different version of the script for each user. With variables, you keep the script the same and only change the user’s name.

Such a script would look something like the following:

How to work with variables in bash

The above example may seem redundant; however, as the complexity of the code increases, variables become indispensable. A script could be hundreds or thousands of lines long and contain the user’s name in different spots. To better understand it, consider the following somewhat different script:

How to work with variables in bash

The above script will use the name defined as the username variable to complete the text. If using the actual user’s name, you’d have to type it four times. Then, do the same for the next user, and another four times for the next. Again and again. By assigning it to a variable, you only have to change it once for each user, and every mention of the user’s name in the text will be updated.

Permanent Bash Variables and Aliases

We saw how you can temporarily set variables and how, for something more permanent, you can include them in your own scripts. Isn’t it possible, though, to permanently set variables in Bash? The answer’s a big “yup!” and you only have to edit a single file: “

/.bashrc” in your favorite text editor. Since I prefer nano, I did it with:

We suggest you begin with a test run, only adding a single variable, so that you’ll know where to look if the process doesn’t work out. Move to the end of the file and, in a new line, add your variable. For example, I set a variable for my name as:

How to work with variables in bash

Save your file and exit the editor. The tweaks won’t be applied immediately. Enter the following in your terminal for it to take effect:

Now you can make use of the newly set variable in your Bash session:

You can set up as many variables as you like and vastly simplify your daily adventures in Bash.

For an extra boost in productivity, it’s also worth setting up a different type of variable: aliases. Unlike typical variables, which are mapped to data you can use in commands, aliases are used instead of actual commands.

Just like you can use a simple-to-remember variable to hold long strings of text, you can use aliases as easy alternatives to complex commands. You can find more about them here, where we turn a whole 7zip compression command into a two-character alias.

As a final note, even if you’ve permanently set a variable in .bashrc, you can re-assign a different value to it temporarily, as we saw before. The variable will present the new content until the current Bash session ends (after logging out or restarting) or you re-source the .bashrc file.

OK’s real life started at around 10, when he got his first computer – a Commodore 128. Since then, he’s been melting keycaps by typing 24/7, trying to spread The Word Of Tech to anyone interested enough to listen. Or, rather, read.

You can use variables in bash as in any programming language. There are no data types so a variable can contain a number, or a string of characters. There is no need to declare a variable, just assign a value:

The VALUE of a variable is retrieved by placing a ‘ $ ‘ before the variable name.

When echoing a variable it is important to surround the variable” in quotes”, otherwise echo will expand the variable and attempt to perform globbing with any files that match in the current directory.

When you reference a variable in bash it is important not to put spaces around the equals sign: STR= 2 , STR = 2 , and STR =2 all mean slightly different things, the extra spaces will not throw a syntax error.

Bash variables may contain the characters: A-Z a-z 0-9 _ they are typically all-caps but lower or mixed case is also supported.

Shell variables are Global within bash, while an environment variable is visible to every process on the OS.

Reading (quoting) a variable

When reading a variable it is often useful to use parameter expansion to clearly indicate the variable name.
For example if you have a variable $MYVAR containing a filename (as a string) and want to do a rename, you might try:

mv “$MYVAR” “$MYVAR_bak ” # this won’t work because bash will expect a variable called MYVAR_bak

Instead, replace $MYVAR with $ which expands to the string value we want.

mv “$MYVAR” “$_bak “

Example – using the $? shell parameter to obtain an exit code from ls.

Shell and environment variables:

The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the echo, set and unset commands.

The system maintains its own list of ‘environment’ variables. These can be displayed and changed with printenv , setenv and unsetenv .

(+) Variables may be made read-only with set -r (q.v.)

Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so set -r should be used with caution. Environment variables cannot be made read-only.

Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell’s argument list, and words of this variable’s value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not.
For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell.

Default Shell Variables

Bash automatically assigns default values to a number of variables, which are listed below.
Bash uses the 10 shell variables below in the same way as the Bourne shell.

CDPATH A colon-separated list of directories used as a search path for the cd builtin command. HOME The current user’s home directory; the default for the cd builtin command. The value of this variable is also used by tilde expansion. IFS A list of characters that separate fields; used when the shell splits words as part of expansion. By default it is space, tab and newline. MAIL If this parameter is set to a filename and the MAILPATH variable is not set, Bash informs the user of the arrival of mail in the specified file. MAILPATH A colon-separated list of filenames which the shell periodically checks for new mail. Each list entry can specify the message that is printed when new mail arrives in the mail file by separating the file name from the message with a ‘?’ . When used in the text of the message, $_ expands to the name of the current mail file. OPTARG The value of the last option argument processed by the getopts builtin. OPTIND The index of the last option argument processed by the getopts builtin. PATH A colon-separated list of directories in which the shell looks for commands. PS1 The primary prompt string. PS2 The secondary prompt string. The default value is ‘> ‘