How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

my_boost=Tequila in a terminal window

If you re-run the previous command, you now get a different result:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminalwindow

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

Correct an incorrect examples of referencing variables in a terminal window

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

drink_of-the_Year="$my_boost $this_year" in a terminal window

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

chmod +x fcnt2.sh in a terminal window

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

fig13 in a terminal window

Now, you can run it with a bunch of different command line parameters, as shown below.

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

List of environment variables in less in a terminal window

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

site_name=How-To Geek in a terminal window

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

site_name="How-To Geek" in a terminal window

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

Linux Commands

Files

Processes

Networking

  • Linux & macOS Terminal

The Shell Scripting Tutorial

Variables - part 1.

Just about every programming language in existence has the concept of variables - a symbolic name for a chunk of memory to which we can assign values, read and manipulate its contents. The Bourne shell is no exception, and this section introduces that idea. This is taken further in Variables - Part II which looks into variables which are set for us by the environment. Let's look back at our first Hello World example. This could be done using variables (though it's such a simple example that it doesn't really warrant it!) Note that there must be no spaces around the " = " sign: VAR=value works; VAR = value doesn't work. In the first case, the shell sees the " = " symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it. If you think about it, this makes sense - how else could you tell it to run the command VAR with its first argument being "=" and its second argument being "value"? Enter the following code into var.sh:

This assigns the string "Hello World" to the variable MY_MESSAGE then echo es out the value of the variable. Note that we need the quotes around the string Hello World. Whereas we could get away with echo Hello World because echo will take any number of parameters, a variable can only hold one value, so a string with spaces must be quoted so that the shell knows to treat it all as one. Otherwise, the shell will try to execute the command World after assigning MY_MESSAGE=Hello

The shell does not care about types of variables; they may store strings, integers, real numbers - anything you like. People used to Perl may be quite happy with this; if you've grown up with C, Pascal, or worse yet Ada, this may seem quite strange. In truth, these are all stored as strings, but routines which expect a number can treat them as such. If you assign a string to a variable then try to add 1 to it, you will not get away with it:

This is because the external program expr only expects numbers. But there is no syntactic difference between:

Note though that special characters must be properly escaped to avoid interpretation by the shell. This is discussed further in Chapter 6, Escape Characters .

We can interactively set variable names using the read command; the following script asks you for your name then greets you personally:

Mario Bacinsky kindly pointed out to me that I had originally missed out the double-quotes in the final line, which meant that the single-quote in the word "you're" was unmatched, causing an error. It is this kind of thing which can drive a shell programmer crazy, so watch out for them!

Scope of Variables

Variables in the Bourne shell do not have to be declared, as they do in languages like C. But if you try to read an undeclared variable, the result is the empty string. You get no warnings or errors. This can cause some subtle bugs - if you assign MY_OBFUSCATED_VARIABLE=Hello and then echo $MY_OSFUCATED_VARIABLE Then you will get nothing (as the second OBFUSCATED is mis-spelled).

There is a command called export which has a fundamental effect on the scope of variables. In order to really know what's going on with your variables, you will need to understand something about how this is used.

Create a small shell script, myvar2.sh :

Now run the script:

MYVAR hasn't been set to any value, so it's blank. Then we give it a value, and it has the expected result. Now run:

It's still not been set! What's going on?! When you call myvar2.sh from your interactive shell, a new shell is spawned to run the script. This is partly because of the #!/bin/sh line at the start of the script, which we discussed earlier . We need to export the variable for it to be inherited by another program - including a shell script. Type:

Now look at line 3 of the script: this is changing the value of MYVAR . But there is no way that this will be passed back to your interactive shell. Try reading the value of MYVAR :

Once the shell script exits, its environment is destroyed. But MYVAR keeps its value of hello within your interactive shell. In order to receive environment changes back from the script, we must source the script - this effectively runs the script within our own interactive shell, instead of spawning another shell to run it. We can source a script via the "." (dot) command:

The change has now made it out into our shell again! This is how your .profile or .bash_profile file works, for example. Note that in this case, we don't need to export MYVAR . An easy mistake to make is to say echo MYVAR instead of echo $MYVAR - unlike most languages, the dollar ( $ ) symbol is required when getting the value of a variable, but must not be used when setting the value of the variable. An easy mistake to make when starting out in shell scripting. One other thing worth mentioning at this point about variables, is to consider the following shell script:

Think about what result you would expect. For example, if you enter "steve" as your USER_NAME, should the script create steve_file ? Actually, no. This will cause an error unless there is a variable called USER_NAME_file . The shell does not know where the variable ends and the rest starts. How can we define this? The answer is, that we enclose the variable itself in curly brackets :

The shell now knows that we are referring to the variable USER_NAME and that we want it suffixed with " _file ". This can be the downfall of many a new shell script programmer, as the source of the problem can be difficult to track down.

Also note the quotes around "${USER_NAME}_file" - if the user entered "Steve Parker" (note the space) then without the quotes, the arguments passed to touch would be Steve and Parker_file - that is, we'd effectively be saying touch Steve Parker_file , which is two files to be touch ed, not one. The quotes avoid this. Thanks to Chris for highlighting this.

Get this tutorial as a PDF for only $5

My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.


Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion.

Also available in PDF form from Gumroad:

Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script.

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

How to Set Variables in Bash: Shell Script Syntax Guide

Bash script setting a variable depicted with assignment symbols and variable name icons highlighting equal signs and data assignment markers

Do you find setting variables in Bash a bit tricky? You’re not alone. Many developers find Bash variable assignment a bit puzzling, but we’re here to help! You can think of Bash variables as small storage boxes – they allow us to store data temporarily for later use, providing a versatile and handy tool for various tasks.

In this guide, we’ll walk you through the process of setting variables in Bash , from the basics to more advanced techniques. We’ll cover everything from simple variable assignment, manipulating and using variables, to more complex uses such as setting environment variables or using special variable types.

So, let’s dive in and start mastering Bash variables!

TL;DR: How Do I Set a Variable in Bash?

To set a variable in Bash, you use the '=' operator with the syntax, VAR=Value . There must be no spaces between the variable name, the '=' operator, and the value you want to assign to the variable.

Here’s a simple example:

In this example, we’ve set a variable named VAR to the string ‘Hello, World!’. We then use the echo command to print the value of VAR , resulting in ‘Hello, World!’ being printed to the console.

This is just the basics of setting variables in Bash. There’s much more to learn about using variables effectively in your scripts. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Bash Variable Basics: Setting and Using Variables

Advanced bash variable usage, alternative approaches to bash variables, troubleshooting bash variables: common pitfalls and solutions, understanding variables in programming and bash, expanding bash variable usage in larger projects, wrapping up: mastering bash variables.

In Bash, setting a variable is a straightforward process. It’s done using the ‘=’ operator with no spaces between the variable name, the ‘=’ operator, and the value you want to assign to the variable. Let’s dive into a basic example:

In this example, we’ve created a variable named myVar and assigned it the value ‘Bash Beginner’. The echo command is then used to print the value of myVar , which results in ‘Bash Beginner’ being printed to the console.

The advantages of using variables in Bash are numerous. They allow you to store and manipulate data, making your scripts more flexible and efficient. However, there are potential pitfalls to be aware of. One common mistake is adding spaces around the ‘=’ operator when assigning values to variables. In Bash, this will result in an error.

Here’s what happens when you add spaces around the ‘=’ operator:

As you can see, Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

As you progress in Bash scripting, you’ll encounter instances where you need to use more advanced techniques for setting variables. One such technique is setting environment variables, which are variables that are available system-wide and to other programs. Another is using special variable types, such as arrays.

Setting Environment Variables

Environment variables are an essential part of Bash scripting. They allow you to set values that are going to be used by other programs or processes. To create an environment variable, you can use the export command:

In this example, we’ve created an environment variable called GREETING with the value ‘Hello, World!’. The export command makes GREETING available to child processes.

Using Array Variables

Bash also supports array variables. An array is a variable that can hold multiple values. Here’s how you can create an array variable:

In this case, we’ve created an array myArray containing three elements. We then print the second element (arrays in Bash are zero-indexed, so index 1 corresponds to the second element) using the echo command.

These are just a couple of examples of the more advanced ways you can use variables in Bash. As you continue to learn and experiment, you’ll find that variables are a powerful tool in your Bash scripting arsenal.

While setting variables in Bash is typically straightforward, there are alternative approaches and techniques that can offer more flexibility or functionality in certain scenarios. These can include using command substitution, arithmetic expansion, or parameter expansion.

Command Substitution

Command substitution allows you to assign the output of a command to a variable. This can be particularly useful for dynamic assignments. Here’s an example:

In this example, we’ve used command substitution ( $(command) ) to assign the current date to the myDate variable.

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. For instance:

Here, we’ve used arithmetic expansion ( $((expression)) ) to add 5 and 5 and assign the result to the num variable.

Parameter Expansion

Parameter expansion provides advanced operations and manipulations on variables. This can include string replacement, substring extraction, and more. Here’s an example of string replacement:

In this case, we’ve used parameter expansion ( ${variable/search/replace} ) to replace ‘World’ with ‘Reader’ in the greeting variable.

These alternative approaches provide advanced ways of working with variables in Bash. They can offer more functionality and flexibility, but they also come with their own considerations. For instance, they can make scripts more complex and harder to read if not used judiciously. As always, the best approach depends on the specific task at hand.

While working with Bash variables, you might encounter some common errors or obstacles. Understanding these can help you write more robust and effective scripts.

Unassigned Variables

One common mistake is trying to use a variable that hasn’t been assigned a value. This can lead to unexpected behavior or errors. For instance:

In this case, because unassignedVar hasn’t been assigned a value, nothing is printed to the console.

Spaces Around the ‘=’ Operator

As mentioned earlier, adding spaces around the ‘=’ operator when assigning values to variables will result in an error:

Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

Variable Name Considerations

Variable names in Bash are case-sensitive, and can include alphanumeric characters and underscores. However, they cannot start with a number. Trying to create a variable starting with a number results in an error:

In this case, Bash doesn’t recognize 1var as a valid variable name and throws an error.

Best Practices and Optimization

When working with Bash variables, it’s good practice to use descriptive variable names. This makes your scripts easier to read and understand. Also, remember to unset variables that are no longer needed, especially in large scripts. This can help to optimize memory usage.

Understanding these common pitfalls and best practices can help you avoid errors and write better Bash scripts.

Variables are a fundamental concept in programming. In simple terms, a variable can be seen as a container that holds a value. This value can be a number, a string, a file path, an array, or even the output of a command.

In Bash, variables are used to store and manipulate data. The data stored in a variable can be accessed by referencing the variable’s name, preceded by a dollar sign ($).

Here is an example:

In this example, we have a variable named website that holds the value ‘www.google.com’. The echo command is used to print the value of the website variable, resulting in ‘www.google.com’ being output to the console.

Variables in Bash can be assigned any type of value, and the type of the variable is dynamically determined by the value it holds. This is different from some other languages, where the variable type has to be declared upon creation.

In addition to user-defined variables, Bash also provides a range of built-in variables, such as $HOME , $PATH , and $USER , which hold useful information and can be used in your scripts.

Understanding how variables work in Bash, and in programming in general, is crucial for writing effective scripts and automating tasks.

Setting variables in Bash is not just limited to small scripts. They play a crucial role in larger scripts or projects, helping to store and manage data effectively. The use of variables can streamline your code, making it more readable and maintainable.

Leveraging Variables in Scripting

In larger scripts, variables can be used to store user input, configuration settings, or the results of commands that need to be used multiple times. This can help to make your scripts more dynamic and efficient.

Accompanying Commands and Functions

When setting variables in Bash, you might often find yourself using certain commands or functions. These can include echo for printing variable values, read for getting user input into a variable, or unset for deleting a variable. Understanding these accompanying commands and functions can help you get the most out of using variables in Bash.

In this example, the read command is used to get user input and store it in the name variable. The echo command then uses this variable to greet the user.

Further Resources for Bash Variable Mastery

To deepen your understanding of Bash variables and their usage, you might find the following resources helpful:

  • GNU Bash Manual : This is the official manual for Bash, and it provides a comprehensive overview of all its features, including variables.

Bash Scripting Guide : This is a detailed guide to Bash scripting, with plenty of examples and explanations.

Bash Variables : This tutorial offers a detailed look at Bash variables, including their declaration, assignment, and usage.

These resources offer in-depth information about Bash variables and related topics, and can provide valuable insights as you continue your Bash scripting journey.

In this comprehensive guide, we’ve delved deep into the world of Bash variables. From simple variable assignment to more complex uses such as setting environment variables or using special variable types, we’ve covered it all.

We began with the basics, showing you how to set and use variables in Bash. We then explored more advanced techniques, such as setting environment variables and using array variables. Along the way, we also discussed alternative approaches, including command substitution, arithmetic expansion, and parameter expansion.

We also tackled common pitfalls and provided solutions to help you avoid these errors. Additionally, we compared the different methods of setting variables and their benefits, giving you a broader understanding of Bash variables.

MethodProsCons
Simple Variable AssignmentSimple and straightforwardLimited to single values
Environment VariablesAvailable system-wideCould affect other processes
Array VariablesCan hold multiple valuesMore complex to use
Command SubstitutionDynamic assignmentsDepends on command output
Arithmetic ExpansionAllows arithmetic operationsLimited to numeric values
Parameter ExpansionAdvanced string operationsCan make scripts complex

Whether you’re just getting started with Bash scripting or you’re looking to advance your skills, we hope this guide has given you a deeper understanding of Bash variables and how to use them effectively.

Mastering Bash variables is a key step in becoming proficient in Bash scripting. With the knowledge and techniques you’ve gained from this guide, you’re now well-equipped to use variables effectively in your scripts. Happy scripting!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Linux_penguin_mascot_USB_devices_abstract_depiction2

  • Shell Scripting
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question

Shell Scripting – Shell Variables

A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing the shell variable scripting leads us to write strong and good shell scripts.

Rules for variable definition

 A variable name could contain any alphabet (a-z, A-Z), any digits (0-9), and an underscore ( _ ). However, a variable name must start with an alphabet or underscore. It can never start with a number. Following are some examples of valid and invalid variable names:

  • Valid Variable Names
  • Invalid variable names 

Note: It must be noted that no other special character except underscore can be used in a variable name because all other special characters have special meanings in Shell Scripting.

Defining Variables

These kinds of variables are scalar variables as they could hold one value at a time. 

1) Accessing variable

Variable data could be accessed by appending the variable name with ‘$’ as follows:

Accessing variable

Example of Accessing variable

2) Unsetting Variables

The unset command directs a shell to delete a variable and its stored data from list of variables. It can be used as follows:

Unsetting Variables

Example of Unsetting Variables

Note: The unset command could not be used to unset read-only variables.

3) Read only Variables.

These variables are read only i.e., their values could not be modified later in the script. Following is an example:

Read only Variables.

Example of Read only Variables.

Now let us see all the above codes in action together. Following is a shell script that includes all the shell variables discussed above.

linux shell script variable assignment

All outputs

Variable Types

We can discuss three main types of variables:

1) Local Variable:

Variables which are specific to the current instance of shell. They are basically used within the shell, but not available for the program or other shells that are started from within the current shell. 

For example: 

`name=Jayesh`    

In this case the local variable is (name) with the value of Jayesh. Local variables is temporary storage of data within a shell script.

2) Environment Variable:

These variables are commonly used to configure the behavior script and programs that are run by shell. Environment variables are only created once, after which they can be used by any user.

For example:

`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of the shell’s search path for executable programs.

3) Shell Variables:

Variables that are set by shell itself and help shell to work with functions correctly. It contains both, which means it has both, some variables are Environment variable, and some are Local Variables.

`$PWD` = Stores working directory 

`$HOME` = Stores user’s home directory

`$SHELL` = Stores the path to the shell program that is being used.

Few more examples in Shell Scripting and Shell Variable

How to store user data in a variable.

In this example the variables ‘length’, ‘width’ and ‘area’ are used to store user input and calculate the area of the rectangle.

Giving input to variables

Giving input to the variable

In this ‘echo’ is a command used to print the statement and ‘read’ is a command used to take data from user and store it in a variable.

To Store and Display Message

We can write a script in which we will display a message to the user by looking at the time of the day. In this we can use shell variable to store and display our message.

To Store and Display Message by variables

Getting output based on the time of the day.

In this ‘time’ is a variable storing hours, ‘date’ is a command used to get the current time and ‘%H’ is used to extract only hour’s part. ‘-lt’ is an operator used for numerical comparison it is a less than. ‘fi’ is used to mark the end of ‘if’ statement. 

What is Shell and Its Type?

It is a program that provides a user interface that is used to access operating system services. Or we can say that it is an environment in which we can run our programs and shell scripts etc. It is the core of the operating system. 

There are several different types of shell available. Some common types of shells include:

  • Bourne Shell (sh): The original shell of UNIX operating system. It has been used for scripting purposes and also to provide basic commands.
  • C Shell (csh): This is also a popular shell for UNIX operating system. As the name suggests, its syntax is similar to C programming language.
  • Bourne-Again Shell (bash): It is a widely used shell for macOS and Linux operating systems. It is more advanced than the original Bourne shell and also has many features that are found in the Korn shell and C shell.

What is Shell Variable Used For?

Shell Variables are used to store data and information within a shell (terminal), and they are also used for controlling the behavior of program and scripts. Some of the common uses are:

  • Setting environment variables.
  • Storing configuration data.
  • Storing temporary data.
  • Passing arguments to scripts.

What is Shell Variable and Shell Scripting?

Shell Variable is used in shell scripts for many functionalities like storing data and information, taking input from users, printing values that are stored. They are also used for storing data temporarily and storing output of commands.

Shell Scripting is a way of writing scripts of programs that are executed in a terminal or shell. Basically, it is a program or script which is written with the help of variables mentioned in it. It is powerful because it can automate tasks, and in this one can use programming constructs that are available in shell, such as loops, conditionals and functions.

Conclusion: 

Shell variables are an essential part of shell scripting. Shell variables allow us to use them anywhere in the script. In this article we have discussed the rules for defining scalar variables, unsetting variables, read-only variables and accessing variables. This article will serve as a helpful guide for beginners and those who want to understand how to write shell script must know how to work with shell variables.

Please Login to comment...

Similar reads.

  • Shell Script
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Linux Guides, Tips and Tutorials | LinuxScrew

Home » Linux » Shell » Bash Variables

Bash Variables and How to Use Them

Variables in Bash/Shell Scripts and How To Use Them [Tutorial]

This article will show you how to use variables in Bash and Shell scripts in Linux.

Bash  (or  Linux Shell ) scripts are files you write containing commands to automate common tasks and save yourself some time.

Variables are things in scripts that hold a value for later use – a number, or a filename, or anything, really.

Here’s how to define and use variables in Linux Shell scripts. These examples should work in the most popular Linux Shells,  Bash, and Zsh .

Declaring Bash Variables

Bash VARIABLES ARE UNTYPED by default. You can’t tell  it what can be done with a variable – it’s implied.

Essentially, all variables are stored as strings and handled according to context when they are used – if a string contains a number, it will be treated as one if you try to increment with it, etc.

Below, several variables are declared –  MY_STRING ,  MY_FILE_PATH,  and  MY_NUMBER .  These are all untyped variables.

Click here to find out about the #!

‘declare’ Command Syntax

Note that  declare  is specific to the  Bash  environment and may not be present if you are using a different shell.

The syntax of  declare  is as follows:

  • OPTIONS is optional and can be picked from the below table to set the type or behavior of the variable
  • variable_name  is the name of the variable you wish to define/declare
  • variable_value  is the value of said variable
 option Meaning
-r readonly Declare a read-only variable
-i integer Declare an integer variable
-a array Declare a
-f function(s) Declare a variable which is a function
-x export Declare a

‘declare’ Command Example

Here a string variable is declared (i.e., no OPTIONS  supplied), followed by an integer variable.

Now, if you tried to assign the value of the variable MY_STRING to the value of MY_NUMBER, MY NUMBER would be set to 0 – as the string does not evaluate to a number.

declare offers only basic typing functionality, so it’s not really something to be relied on- but it can be useful for making sure that a variable can only hold a certain type of value.

Using Bash Variables

To use a variable, prefix it with  $  (dollar sign). For example:

Note the use of the  touch  command to create or update the file in the script above.

Note the use of the double brackets (()) – this tells Bash to evaluate the statement contained within them – otherwise, MY_NUMBER would be given a string value containing the characters “$MY NUMBER+1”.

Using Variables in Strings

Sometimes you may need to use a variable’s value in a string – for example, if you’ve collected file paths from user input .

To include a variable in a string, simply use it in the wrapped quotes of another string:

Local Variables

Local variables are only available within the scope in which they are created, i.e., inside the particular function or loop where they are defined.

  • Command Line Arguments in Shell/Bash Scripts [Tutorial]
  • Bash Scripts Set Environmental Variables with EXPORT [HowTo]
  • How to Use Functions in Bash/Shell Scripts, With Examples
  • Bash Split String (+ Shell Scripts)

Photo of author

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Privacy Overview

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Using "${a:-b}" for variable assignment in scripts

I have been looking at a few scripts other people wrote (specifically Red Hat), and a lot of their variables are assigned using the following notation VARIABLE1="${VARIABLE1:-some_val}" or some expand other variables VARIABLE2="${VARIABLE2:-`echo $VARIABLE1`}"

What is the point of using this notation instead of just declaring the values directly (e.g., VARIABLE1=some_val )?

Are there benefits to this notation or possible errors that would be prevented?

Does the :- have specific meaning in this context?

  • shell-script

slm's user avatar

  • 4 Crazy how after 20 years using the shell I have never come to see this notation yet! –  Kiteloopdesign Commented Mar 6, 2023 at 20:37

4 Answers 4

This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable.

NOTE: This form also works, ${parameter-word} . According to the Bash documentation , for all such expansions:

Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter ’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

If you'd like to see a full list of all forms of parameter expansion available within Bash then I highly suggest you take a look at this topic in the Bash Hacker's wiki titled: " Parameter expansion ".

variable doesn't exist

Variable exists.

The same thing can be done by evaluating other variables, or running commands within the default value portion of the notation.

More Examples

You can also use a slightly different notation where it's just VARX=${VARX-<def. value>} .

In the above $VAR1 & $VAR2 were already defined with the string "has another value" but $VAR3 was undefined, so the default value was used instead, 0 .

Another Example

Checking and assigning using := notation.

Lastly I'll mention the handy operator, := . This will do a check and assign a value if the variable under test is empty or undefined.

Notice that $VAR1 is now set. The operator := did the test and the assignment in a single operation.

However if the value is set prior, then it's left alone.

Handy Dandy Reference Table

Parameter set and not null Parameter set but null Parameter unset
substitute substitute substitute
substitute substitute substitute
substitute assign assign
substitute substitute assign
substitute error, exit error, exit
substitute substitute error, exit
substitute substitute substitute
substitute substitute substitute

( Screenshot of source table )

This makes the difference between assignment and substitution explicit: Assignment sets a value for the variable whereas substitution doesn't.

  • Parameter Expansions - Bash Hackers Wiki
  • 10.2. Parameter Substitution
  • Bash Parameter Expansions

muru's user avatar

  • 18 Using echo "${FOO:=default}" is great if you actually want the echo . But if you don't, then try the : built-in ... : ${FOO:=default} Your $FOO is set to default as above (i.e., if not already set). But there's no echoing of $FOO in the process. –  fbicknel Commented Aug 10, 2017 at 19:50
  • 3 Ok, found an answer: stackoverflow.com/q/24405606/1172302 . Using the ${4:-$VAR} will work. –  Nikos Alexandris Commented Jan 19, 2018 at 9:23
  • 1 It also allows users to provide their own value for a given variable. This can be very useful when working around issues not foreseen at the time the script was written. –  Thorbjørn Ravn Andersen Commented May 1, 2019 at 11:27
  • 1 wiki.bash-hackers.org is currently down: github.com/rawiriblundell/wiki.bash-hackers.org –  Per Lundberg Commented Jun 7, 2023 at 10:49
  • 1 @PerLundberg - ty I've updated it w/ archive.org - web.archive.org/web/20200309072646/https://… . –  slm ♦ Commented Jun 30, 2023 at 20:36

@slm has already included the POSIX docs - which are very helpful - but they don't really expand on how these parameters can be combined to affect one another. There is not yet any mention here of this form:

This is an excerpt from another answer of mine, and I think it demonstrates very well how these work:

Another example from same :

The above example takes advantage of all 4 forms of POSIX parameter substitution and their various :colon null or not null tests. There is more information in the link above, and here it is again .

Another thing that people often don't consider about ${parameter:+expansion} is how very useful it can be in a here-document. Here's another excerpt from a different answer :

Here you'll set some defaults and prepare to print them when called...

This is where you define other functions to call on your print function based on their results...

You've got it all setup now, so here's where you'll execute and pull your results.

I'll go into why in a moment, but running the above produces the following results:

_less_important_function()'s first run: I went to your mother's house and saw Disney on Ice. If you do calligraphy you will succeed.

then _more_important_function():

I went to the cemetery and saw Disney on Ice. If you do remedial mathematics you will succeed.

_less_important_function() again:

I went to the cemetery and saw Disney on Ice. If you do remedial mathematics you will regret it.

HOW IT WORKS:

The key feature here is the concept of conditional ${parameter} expansion. You can set a variable to a value only if it is unset or null using the form:

${var_name := desired_value}

If instead you wish to set only an unset variable, you would omit the :colon and null values would remain as is.

You might notice that in the above example $PLACE and $RESULT get changed when set via parameter expansion even though _top_of_script_pr() has already been called, presumably setting them when it's run. The reason this works is that _top_of_script_pr() is a ( subshelled ) function - I enclosed it in parens rather than the { curly braces } used for the others. Because it is called in a subshell, every variable it sets is locally scoped and as it returns to its parent shell those values disappear.

But when _more_important_function() sets $ACTION it is globally scoped so it affects _less_important_function()'s second evaluation of $ACTION because _less_important_function() sets $ACTION only via ${parameter:=expansion}.

Community's user avatar

Personal experience.

I use this format sometimes in my scripts to do ad-hoc over-riding of values, e.g. if I have:

without having to change the original default value of SOMETHING .

h.j.k.'s user avatar

  • 1 Fancy way of passing/overriding variables to/in a script :) –  Kiteloopdesign Commented Mar 6, 2023 at 20:35

An interesting way of getting a single command-line parameter uses the $1, $2 ... scheme.

Called with parameters: Won too tree

Result: Second parameter: too

Called with parameters: Five!

Result: Second parameter: default2

Engineer's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash shell-script scripting variable ..

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities

Hot Network Questions

  • Stretched space in math mode
  • Is it possible/recommended to paint the side of piano's keys?
  • Generalization of the Schur-Zassenhaus Theorem
  • Fifth year PhD student with no progress on my thesis because of advisor, what to do?
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • Odorless color less , transparent fluid is leaking underneath my car
  • Are these colored sets closed under multiplication?
  • Emergency belt repair
  • What was the newest chess piece
  • Sum of the individual kinetic energies of the particles which make the system the same as the K.E. of the center of mass? What's bad in my reasoning?
  • Copyright on song first performed in public
  • Movie from the fifties where aliens look human but wear sunglasses to hide that they have no irises (color) in their eyes - only whites!
  • How to make a soundless world
  • Modifying Expansion Order with \seq put right
  • Bounded Star Height and corresponding fragments of MSO
  • Why minutes of Latitude and Longitude tick marks point up and left on sectional charts?
  • Would Dicyanoacetylene Make a Good Flamethrower Fuel?
  • Annoying query "specify CRS for layer World Map" in latest QGIS versions
  • Determining Entropy in PHP
  • What is the best way to protect from polymorphic viruses?
  • Subtract 2 voltages and amplify using 1 op-amp
  • Why doesn't Wolfram Alpha give me the correct answer for this?
  • How to fix: "Error dependency is not satisfiable"?
  • View undo history of Windows Explorer on Win11

linux shell script variable assignment

LinuxConfig

Bash Script: Set variable example

If you are writing a Bash script and have some information that may change during the execution of the script, or that normally changes during subsequent executions, then this should be set as a variable. Setting a variable in a Bash script allows you to recall that information later in the script, or change it as needed. In the case of integers, you can increment or decrement variables, which is useful for counting loops and other scenarios.

In this tutorial, you will learn how to set variables and use them in a Bash script on a Linux system . Check some of the examples below to see how variables works.

In this tutorial you will learn:

  • How to set a variable in a Bash script
  • How to use a previously set variable
  • How to use a variable inside of another variable

How to set a variable in a Bash script

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the command.
Conventions – requires given to be executed with root privileges either directly as a root user or by use of command
– requires given to be executed as a regular non-privileged user

How to set variable in Bash script

First, let’s go over how setting a variable is done in a Bash script. This will familiarize you with the syntax so you can easily interpret the coming examples, and eventually write your own from scratch.

Executing the script gives us this output:

This is the probably the most basic example of a variable as possible, but it gets the point across. Let’s go over what is happening here:

  • The name of the variable in this example is simply var .
  • The variable is declared by using an equal sign = .
  • The variable is set to "Hello World" . The quotes are necessary in this case because of the space.
  • In order to call the variable later in the script, we precede it with a dollar sign $ .

Next, look at the examples below to see more practical examples of setting a variable in a Bash script.

Bash Script: Set variable examples

Check out the examples below to see how to set variables within a Bash script.

Here is the result from executing the script:

The lesson to take away from this example is that you can re-use a variable inside of a Bash script.

The lesson to take away from this example is that variables are very useful when reading data from the user, whether they specify that data as flags or as a response to a prompt. There is another lesson here too. Notice that when declaring the $number variable, we use the $directory variable as well. In other words, a variable inside of a variable.

Closing Thoughts

In this tutorial, you learned how to set variables and use them in Bash scripting on a Linux system. As you can see from the examples, using variables is incredibly useful and will be a common staple in most Bash scripts. The examples shown here are basic in order to introduce you to the concept, but it is normal for a Bash script to contain many variables.

Related Linux Tutorials:

  • Mastering Bash Script Loops
  • Nested Loops in Bash Scripts
  • Bash Scripting: Mastering Arithmetic Operations
  • An Introduction to Linux Automation, Tools and Techniques
  • Mastering String Concatenation in Bash Scripting
  • Customizing and Utilizing History in the Shell
  • String Concatenation in Bash Loops
  • Ansible loops examples and introduction
  • Things to do after installing Ubuntu 22.04 Jammy…
  • Bash Scripting: Operators

Linux Forum

Linux-Techi-Logo

How to Use Variables in Shell Scripting

In this post, we will discuss how to use variables in bash shell scripting with examples.

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

System Defined Variables

Linux-Shell-Variables-Meanings

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

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:

User Defined Variables

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.

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

Running the script produces the following output,

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:

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:

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

Read Also : How to Use Conditional Statements in Bash Script

About The Author

Pradeep kumar, 2 thoughts on “how to use variables in shell scripting”, leave a comment cancel reply.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables

Bash Variables

Susmit Das Gupta

Bash variable stores essential data such as strings, numbers, and arrays of a Bash script. Bash programmer uses variables to manipulate data and do necessary arithmetic operations. In this article, I will explore various aspects of the Bash variable. Let’s start and unleash the full potential of the Bash variable.

Table of Contents

What is Bash Variable?

A Bash variable in Linux is a symbolic name or identifier that stores a value or text string. It is a way to store and manipulate data within a Bash script or the Bash environment. Variables in Bash scripts are typically used to hold temporary or user-defined data, making it easier to reference and manipulate values as needed.

Applications of Variables in Bash Scripts

The variable can be used in the following situations:

  • You can use Bash variables to store data .
  • Arithmetic operations can be done using the Bash variable.
  • Taking valuable input from users and preserving it.
  • Bash variable can be used to create dynamic output .
  • The bash variable lets you access the environment variables .

Fundamental Characteristics of Bash Variables

Bash variables maintain some unique characteristics. These are discussed below:

  • Declaring a Variable: Programmers do not need to declare Variables in Bash explicitly. They can assign a value to a variable directly, and Bash will automatically create it.
  • Naming Convention of a Variable: Bash variables are case-sensitive . Var and var are treated as two different variables. You can use underscore(_) between the words of a variable name.
  • Value Assigning in a Variable: Variables are assigned values using the ‘=’ operator. No spaces should be present around the ‘=’ sign. To assign value in variable_name variable, you have to execute the command: variable_name=value
  • Accessing Values of Variable: To access the value stored in a variable, you can use the variable name preceded by a dollar sign(‘$’). To print the value of variable_name, you have to execute the command: echo $variable_name
  • Types of Variables: Bash does not have explicit variable types. All variables are treated as strings by default. However, you can perform numeric operations on variables containing numeric values.
  • Usage of Variables: Variables can be used in various ways, such as arithmetic calculations, string manipulation, command substitution , and passing values between scripts or functions.

Types of Variables in Linux

There are two types of variables. These are system variables and user-defined variables .

  • System variables are variables defined by the system. These variables have been existing since the installation of the operating system. Some of the system variables with their function are given below:
/bin/bash Defines the name of the shell used.
/root Shows the current Working directory.
root Defines the message of the dayfor the system.
pam Defines the message of the day for the system.
root Home directory of the user.
rs=0:di=01;34:ln=01;36:mh=00:pi=40; Used to set the colors the filenames will be displayed for the user.
/usr/bin/lesspipe %s %s Used to invoke input postprocessor.
root Name of the current user.
1 Displays the number of shell levels the current shell is running on top of.
185.185.185.185 54321 12 SSH client information [user IP] [user port] [Linux machine port].
/usr/local/sbin Defines the directories to be searched for bash to find a command.
/dev/pts/0_=/usr/bin/printenv Displays the path to the device associated with the current shell or command.
  • User-defined variables are defined by the users to accomplish the task of the script. User-defined variables are whatever you want as variables in your script.

Some Special Variables in Linux

There are some special variables that stand for some special task. A list of special variables with their operation is given below:

Number of parameters passed to the script.
All the command line parameters are passed to the script.
The exit status of the last process to run.
The Process ID (PID) of the current script.
The username of the user executing the script.
The hostname of the computer running the script.
The number of seconds the script has been running for.
Returns a random number.
Returns the current line number of the script.

Variable Scope in Bash

The scope of a variable in a program or script is a region where the variables have their existence. There are two types of variable scope. These are listed below:

  • Local Variable: If a variable is declared inside a function then it is generally a local variable .
  • Global Variable: If it is declared outside then it is a global variable.

But in the case of a bash script, whether it is written inside a function or outside a function by default is a global variable. To make a variable local, use the ‘local’ keyword.

Input and Export of Bash Variables

The simplest way to take any variable input from the user is to use the read command. Follow the below syntax to take variable input from the user:

read -p  variable_name

The simplest way to export any variable and print it on the terminal is to use the echo command . Follow the following syntax to do this:

echo $variable_name

7 Practical Examples of Working With Bash Variables

Here I have listed 7 examples related to the Bash variable. I believe you will be able to improve your basic knowledge about bash variables by going through these.

1. Declaration and Assignment of Variables in Bash Scripts

Bash variables must be defined with proper name format. Then the programmer might assign a value to that variable or keep the variable empty. Here I will show you a script where I will declare a variable by assigning a value to it. Then print the value of a variable on the terminal. To achieve so, follow the bash script:

The #!/bin/bash interprets that it is a Bash script. Then, the value of the variable a is assigned. Afterward, the echo command printed the value of “a” on the terminal.

The Bash script has printed the value of the variable on the terminal that I have declared.

2. Performing Arithmetic Operations of Variables in Bash Scripting

You can easily use variables in the Bash script. For using variables, you must mention the variable’s name correctly. The programmer can easily manipulate the value of a variable by an arithmetic operation.

Here I will show you a script where the variable is taken from the user as input and then some arithmetic operations will be done on these variables. To know how to perform arithmetic operations of bash variables, follow the below script:

At first, the Bash script has taken numbers a and b as input. Then I did the arithmetic multiplication. And finally, print the multiplication on the terminal.

The Bash script has taken the value of two numbers as input, calculated the multiplication, and printed the result on the terminal.

3. Use of Local and Global Variables in Bash Script

Programmers use a variable as local or global whatever they want. In this example, I will show you how to work with local and global variables. To use local and global variables in bash, follow the below script:

At first number=10 sets a global variable assigning a value 10 to it. Then the addition function is defined and the “number” variable is set as a local variable assigning a value of 10 to it and the same goes for the m variable. After that value of the number variable is added to the value of the m variable and the result is kept to the number variable. Afterward, the value of the number variable is printed on the terminal. Finally, after the end of the addition function, the value of the number variable is printed again. Where the printed value is the value of the global number variable .

The Bash script has worked with local and global variables.

4. Using Array Variables in Bash Script

As a Bash programmer, you might need to use an array as a variable in Bash to preserve string data . Here I have a script where I will show the value of all elements of that script along with a key. To learn more about array variables, follow the below script:

The my_array=(Cook Graeem Lee Wade Mathew Jumpa) command sets the value of the my_array variable. After that the total=${#my_array[*]}  command calculates the length of the my_array variable and prints a line mentioning the total element number on that array. Afterward the for loop prints the value of all values inside of the my_array variable.  Then the next for loop finds the key for all elements and prints all of the elements’ values with the key on the terminal.

The script printed the total number of the elements, all elements of that script along with a key for every element.

5. Command Substitution With Bash Variables

Here I have developed a Bash script that will substitute a command . So, to learn how to substitute commands with bash variables, check the below script:

The variable=$( ls /usr | wc -l ) command has assigned a command to variable. Then the echo Total $variable entries on usr directory command has printed a text on the terminal.

A variable has substituted a command and printed the output of the command on the terminal.

6. Working With Environment Variables

Here, I will develop a Bash script that will print the SHELL, PWD, HOME and USER variable values which are environment variables . To know how to work with environment variables, check the below script:

The echo "This user is using $SHELL shell" , echo "Their working directory is: $PWD" , echo "While their home directory is: $HOME" , and echo "And the user name is: $USER" commands have printed the SHELL , PWD , HOME, and USER variable values respectively which are environment variables.

The Bash script has printed the SHELL, PWD, HOME, and USER variable values on the terminal which are environment variables.

7. Quoting String in a Bash Variable

Here I will show you a Bash script that will print the string from the variable along with another string utilizing the quotes . To know how to quote string in a bash variable, check out the below script:

The quotes="Command-line arguments" command has assigned a string to the quotes variable. Then the echo "Quotes work like this: $quotes" command has printed the string from the variable along with another string.

The Bash script has printed the string from the variable along with another string utilizing the quotes.

In conclusion, I would like to say that the Bash variable is one of the most important parts of the Bash script. It makes the Bash script more effective for solving problems and automating tasks. After going through this article, I believe you will be productive enough to use the Bash variable on the script.

People Also Ask

What is the use of a variable in bash.

Bash variable stores string or number temporarily. The bash variable is an integral part of Bash scripting. It enables users to write Bash scripts to solve complex problems.

What are the rules for naming variables in bash?

Variable names can contain alphanumeric characters and underscores . It can start with nothing but numbers.

Are bash variables all stored as strings?

Bash variable stores all types of data in a variable as a string . By giving proper instructions, programmers can do arithmetic operations and comparisons on variables.

Where is the shell variable set?

The shell contains the shell variables. They are often used to keep track of ephemeral data, like the current working directory.

  • What is Variable in Programming? [The Complete Guide]
  • Introduction to Variables in Bash Scripting [An Ultimate Guide]
  • Variable Declaration and Assignment
  • Types of Variables in Bash
  • Variable Scopes in Bash
  • Using Variables in Bash Scripting

<< Go Back to  Bash Scripting Tutorial

Susmit Das Gupta

Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

Linux Bash: Multiple Variable Assignment

Last updated: March 18, 2024

linux shell script variable assignment

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Overview

Assigning multiple variables in a single line of code is a handy feature in some programming languages, such as Python and PHP.

In this quick tutorial, we’ll take a closer look at how to do multiple variable assignment in Bash scripts.

2. Multiple Variable Assignment

Multiple variable assignment is also known as tuple unpacking or iterable unpacking.

It allows us to assign multiple variables at the same time in one single line of code.

Let’s take a look at a simple Python example to understand what multiple variable assignment looks like:

In the example above, we assigned three string values to three variables in one shot.

Next, let’s prove if the values are assigned to variables correctly using the  print() function:

As the output shows, the assignment works as we expect.

Using the multiple variable assignment technique in Bash scripts can make our code look compact and give us the benefit of better performance, particularly when we want to assign multiple variables by the output of expensive command execution.

For example, let’s say we want to assign seven variables – the calendar week number, year, month, day, hour, minute, and second – based on the current date. We can straightforwardly do:

These assignments work well.

However, during the seven executions of the date commands, the current time is always changing, and we could get unexpected results.

Further, we’ll execute the date command seven times. If the command were an expensive process, the multiple assignments would definitely hurt the performance.

We can tweak the output format to ask the date command to output those required fields in one single shot:

In other words, if we can somehow use the multiple variable assignment technique, we merely need to execute the date command once to assign the seven variables, something like:

Unfortunately, not all programming languages support the multiple variable assignment feature. Bash and shell script don’t support this feature.  Therefore, the assignment above won’t work.

However, we can achieve our goal in some other ways.

Next, let’s figure them out.

3. Using the read Command

The read command is a powerful Bash built-in utility to read standard input (stdin) to shell variables.

It allows us to assign multiple variables at once:

We use the -r option in the example above to disable backslash escapes when it reads the values.

However, the read command reads from stdin. It’s not so convenient to be used as variable assignments in shell scripts. After all, not all variables are assigned by user inputs.

But there are some ways to redirect values to stdin. Next, let’s see how to do it.

3.1. Using Process Substitution and IO Redirection

We know that we can use “ < FILE ” to redirect FILE  to stdin. Further, process substitution can help us to make the output of a command appear like a file.

Therefore, we can combine the process substitution and the IO redirection together to feed the  read command :

Let’s test it with the previous date command and seven variables’ assignment problem:

As the output above shows, we’ve assigned seven variables in one shot using the process substitution and IO redirection trick.

3.2. Using Command Substitution and the Here-String

Alternatively, we can use the here-string to feed the stdin of the read command:

If we replace the hard-coded string with a command substitution , we can set multiple variables using a command’s output.

Let’s test with the seven variables and the date command scenario:

We’ve assigned seven variables in one shot. Also, the date command is executed only once.

Thus, the read command can help us to achieve multiple variables assignment.

3.3. Changing the Delimiter

The  read command will take the value of the IFS   variable as the delimiter.  By default, it’s whitespace.

But we know that the output of a command is not always delimited by whitespace.

Let’s change the output format of the date command:

This time, the output is delimited by the ‘@’ character and has three fields: the week number, the current date and time, and the weekday of the current date. The second field contains a space.

Now, we’re about to assign the three fields to three variables in one shot.

Obviously, it won’t work with the default delimiter. We can change the delimiter by setting the IFS  variable:

It’s worthwhile to mention that in the example above, the change to the IFS variable only affects the  read command following it.

4. Using an Array

Another way to assign multiple variables using a command’s output is to assign the command output fields to an array.

Let’s show how it works with the date command and seven variables example:

In the example, we used the Bash built-in  readarray command to read the date command’s output.

The default delimiter used by the readarray command is a newline character . But we can set space as the delimiter using the -d option.

5. Conclusion

In this article, we’ve learned what the multiple variable assignment technique is.

Further, we’ve addressed how to achieve multiple variable assignment in Bash scripts through examples, even though Bash doesn’t support this language feature.

Previous: Bourne Shell Variables , Up: Shell Variables   [ Contents ][ Index ]

5.2 Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ).

($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

The full pathname used to execute the current instance of Bash.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see The Shopt Builtin ). The options appearing in BASHOPTS are those reported as ‘ on ’ by ‘ shopt ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. (see Bourne Shell Builtins ). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset.

An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source ) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC . The shell sets BASH_ARGC only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV . The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

When referenced, this variable expands to the name of the shell or shell script (identical to $0 ; See Special Parameters , for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0 . If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin (see Bourne Shell Builtins ). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset.

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

The value is used to set the shell’s compatibility level. See Shell Compatibility Mode , for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see Shell Compatibility Mode ). For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value.

If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See Bash Startup Files .

The command argument to the -c invocation option.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file ( ${BASH_SOURCE[$i+1]} ) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command (see Conditional Constructs ). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the n th parenthesized subexpression.

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset.

A readonly array variable (see Arrays ) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:

The major version number (the release ).

The minor version number (the version ).

The patch level.

The build version.

The release status (e.g., beta1 ).

The value of MACHTYPE .

The version number of the current instance of Bash.

If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘ set -x ’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.

Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX -mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.

Used by the select command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE} . This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB , for normal completion, ‘ ? ’, for listing completions after successive tabs, ‘ ! ’, for listing alternatives on partial word completion, ‘ @ ’, to list completions if the word is not unmodified, or ‘ % ’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The key (or final key of a key sequence) used to invoke the current completion function.

The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset.

An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion ). Each array element contains one possible completion.

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ).

An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If Bash finds this variable in the environment when the shell starts with value ‘ t ’, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

Expanded and executed similarly to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ).

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset.

The numeric effective user id of the current user. This variable is readonly.

A colon-separated list of shell patterns (see Pattern Matching ) defining the list of filenames to be ignored by command search using PATH . Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [ , test , and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE . Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option.

The editor used as a default by the -e option to the fc builtin command.

A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ‘ .o:~ ’

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main" . This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE . Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]} . The caller builtin displays the current call stack using this information.

If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.

A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE , it is removed from the list of matches. The pattern matching honors the setting of the extglob shell option.

An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

Up to three characters which control history expansion, quick substitution, and tokenization (see History Expansion ). The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally ‘ ! ’. The second character is the character which signifies ‘quick substitution’ when seen as the first character on a line, normally ‘ ^ ’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually ‘ # ’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.

The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.

A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ‘ ignorespace ’, lines which begin with a space character are not saved in the history list. A value of ‘ ignoredups ’ causes lines which match the previous history entry to not be saved. A value of ‘ ignoreboth ’ is shorthand for ‘ ignorespace ’ and ‘ ignoredups ’. A value of ‘ erasedups ’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE . The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL .

The name of the file to which the command history is saved. The default value is ~/.bash_history .

The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.

A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit ‘ * ’ is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, ‘ & ’ matches the previous history line. ‘ & ’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE . The pattern matching honors the setting of the extglob shell option.

HISTIGNORE subsumes the function of HISTCONTROL . A pattern of ‘ & ’ is identical to ignoredups , and a pattern of ‘ [ ]* ’ is identical to ignorespace . Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth .

The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.

If this variable is set and not null, its value is used as a format string for strftime to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

The name of the current host.

A string describing the machine Bash is running on.

Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

The name of the Readline initialization file, overriding the default of ~/.inputrc .

If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of TERM .

Used to determine the locale category for any category not specifically selected with a variable starting with LC_ .

This variable overrides the value of LANG and any other LC_ variable specifying a locale category.

This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale-Specific Translation ).

This variable determines the locale category used for number formatting.

This variable determines the locale category used for data and time formatting.

The line number in the script or shell function currently executing. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

Used by the select command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.

How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

The previous working directory as set by the cd builtin.

If set to the value 1, Bash displays error messages generated by the getopts builtin command.

A string describing the operating system Bash is running on.

An array variable (see Arrays ) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

If this variable is in the environment when Bash starts, the shell enters POSIX mode (see Bash POSIX Mode ) before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command

had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set.

The process ID of the shell’s parent process. This variable is readonly.

If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt ( $PS1 ). If this is set but not an array variable, its value is used as a command to execute instead.

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Controlling the Prompt ). Characters removed are replaced with an ellipsis.

The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed.

The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with ‘ #? ’

The value of this parameter is expanded like PS1 and the expanded value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin ). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ‘ + ’.

The current working directory as set by the cd builtin.

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Any numeric argument given to a Readline command that was defined using ‘ bind -x ’ (see Bash Builtin Commands when it was invoked.

The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ). The characters between the insertion point and the mark are often called the region .

The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The default variable for the read builtin.

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see The Set Builtin ). The options appearing in SHELLOPTS are those reported as ‘ on ’ by ‘ set -o ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random , so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘ % ’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

A literal ‘ % ’.

The elapsed time in seconds.

The number of CPU seconds spent in user mode.

The number of CPU seconds spent in system mode.

The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MM m SS . FF s. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtin Commands ). The select command (see Conditional Constructs ) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.

In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.

If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use.

The numeric real user id of the current user. This variable is readonly.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

how to assign variable in shell script

I have below shell script code which is working fine.

But currently i can run this code only on dev database as you can see in run function script the import.dev.properties.TODO is set as dev. I want to make this flexible such that if the path is "/tmp/in/simu" for simu_path variable then the properties should be import.simu.properties.TODO and for dev_path it should be import.dev.properties.TODO so that it will run on the respective database.

I am not sure if its possible to set parametarized variable here. For example something like this import.${varaible_here_dev_or_simu}.properties.TODO

I want to keep the dev_path and simu_path as it is as it can be changed as i am passing this in argument

  • command-line

Andrew's user avatar

  • It would make your run function a lot easier to read if you put each statement on a separate line. –  Tom Fenech Commented Feb 5, 2020 at 10:24
  • import.$(basename "$1").properties.TODO ? –  KamilCuk Commented Feb 5, 2020 at 10:26
  • @TomFenech sure i did this..@kamil i will try with import.$(basename "$1").properties.TODO –  Andrew Commented Feb 5, 2020 at 10:27
  • If it's one long command, don't forget to escape the newlines with \ (I edited to do that) –  Tom Fenech Commented Feb 5, 2020 at 10:31

2 Answers 2

Change import.dev.properties.TODO to import."$2".properties.TODO in run function. And use it like this.

And we could ref this a bit

Ivan's user avatar

  • i dont understand "$whatever_you_name_it" what should i put here ...can you please explain ? –  Andrew Commented Feb 5, 2020 at 10:29
  • 1 Whatever you want in place of $2 in import."$2".properties.TODO –  Federico klez Culloca Commented Feb 5, 2020 at 10:30
  • i think in this case should i use if condition instead of case beacause i am putting case condition togethere "$dev_path" | "$simu_path" so not understood –  Andrew Commented Feb 5, 2020 at 10:32
  • i think this syntax needs to changed in case condition dev|simu ? and also what argument should i pass while running the script ? previous i was running like like ./script.sh "/tmp/in" and the main problem is i dont want to change dev_path or simu path as this path i am pasiing in argument while running and it can be little bit different –  Andrew Commented Feb 5, 2020 at 10:41
  • i have updated my answer ..as i said what if my dev_path and simu_path are like this then i think this will not work.. –  Andrew Commented Feb 5, 2020 at 10:56

As far as I know, bash unfortunately does not support constructs like associative arrays, which could be a possible solution, prior version 4.

If the paths for the environments all look like the same, you could write it like this.

Note: In this implementation you would have to pass dev or simu to the script instead of the whole path. If you need to pass the complete path you have to change the "$dev_env" | "$simu_env" ) to "$base_path/$dev_env" | "$base_path/$simu_env" )

Assuming the path structure and the environments are fixed, you can extract the environment with a simple regex and pass it to the function as the seconds parameter, like so:

Jan Held's user avatar

  • the main problem is i dont want to change dev_path or simu path as this path i am pasiing in argument while running and it can be little bit different.. i have mentioned this in question –  Andrew Commented Feb 5, 2020 at 10:47
  • Okay understood. Another option would be to put create two arrays. One with the paths and a second with the corresponding environments. You would need a function to determine the index in the paths array and use it to get the correct value from the environments array. Seems a bit ugly but would work. –  Jan Held Commented Feb 5, 2020 at 11:03
  • can we just simply put simu or dev wherever in mode and pass it the same during running the script..for example ./script.sh "dev" or ./script.sh "simu" then it will put the dev or simu variable value wherever necessary in script ? because right now my dev_path and simu_path are not fixed –  Andrew Commented Feb 5, 2020 at 11:04
  • As long as there is a specific naming scheme in your paths, you could extract the value. Otherwise you need to bring the path and environment together somehow. –  Jan Held Commented Feb 5, 2020 at 11:17
  • 1 I updated my post. Simply spoken, you can extract the environment with a line like this: environment=$(echo $mode | sed -E "s/.*(dev|simu).*/\\1/") –  Jan Held Commented Feb 5, 2020 at 13:21

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged bash shell command-line or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • crontab schedule on Alpine Linux runs on days it's not supposed to run on
  • If someone threatens force to prevent another person from leaving, are they holding them hostage?
  • Convert base-10 to base-0.1
  • QGIS Atlas: Export attribute table of atlas features as a CSV
  • Movie from the fifties where aliens look human but wear sunglasses to hide that they have no irises (color) in their eyes - only whites!
  • Stuck as a solo dev
  • Why did the Chinese government call its actual languages 'dialects'? Is this to prevent any subnational separatism?
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • Counting the number of meetings
  • A coworker says I’m being rude—only to him. How should I handle this?
  • Smallest prime q such that concatenation (p+q)"q is a prime
  • Recover lost disk space (> 270 GB)
  • How can we speed up the process of returning our lost luggage?
  • Why is Germany looking to import workers from Kenya, specifically?
  • What is an apologetic to confront Schellenberg's non-resistant divine hiddenness argument?
  • How to see material properties (colors) in main view
  • Why minutes of Latitude and Longitude tick marks point up and left on sectional charts?
  • Missed the application deadline for a TA job. Should I contact them?
  • How to plausibly delay the creation of the telescope
  • Fill this Sudoku variant so that the sums of numbers in the outlined regions are all different
  • Does the different strength of gravity at varying heights affect the forces within a suspended or standing object
  • What was the newest chess piece
  • Sum of the individual kinetic energies of the particles which make the system the same as the K.E. of the center of mass? What's bad in my reasoning?
  • Odorless color less , transparent fluid is leaking underneath my car

linux shell script variable assignment

IMAGES

  1. How to Use Variables in Shell Scripting

    linux shell script variable assignment

  2. Shell Scripting 101: Variables in Shell Scripts

    linux shell script variable assignment

  3. assigning values to variables in shell script

    linux shell script variable assignment

  4. assigning values to variables in shell script

    linux shell script variable assignment

  5. How to Use Variables in Bash Shell Scripts

    linux shell script variable assignment

  6. How to Assign Variable in Bash Script? [8 Practical Cases]

    linux shell script variable assignment

VIDEO

  1. shell vs environment variables (and env, export, etc.) (intermediate) anthony explains #547

  2. Advanced Shell Script Program

  3. Vowel Check Shell Script

  4. Unix

  5. Linux Shell Script

  6. Bash Basics -- How to Use declare and array on Linux

COMMENTS

  1. How to Assign Variable in Bash Script? [8 Practical Cases]

    Learn how to assign variables in Bash scripts using different methods, such as local and global variables, single and multiple assignments, arithmetic operations, and command-line arguments. See practical cases and examples for each method and compare them with the query options.

  2. How to Work with Variables in Bash

    Learn how to create, use, and modify variables in Bash scripts and command line. See examples of string and numeric variables, command substitution, and special variables.

  3. How to Use Variables in Bash Shell Scripts

    Learn how to use variables in bash shell scripts to store and manipulate data. Find out how to declare, assign, change, and access variables, as well as how to use command substitution and constant variables.

  4. Assign values to shell variables

    Learn how to create and set variables within a shell script using the = (equal) sign. See examples of how to display, use and avoid common errors with variables.

  5. Understanding Shell Script Variables

    Learn how to use variables in shell scripts, such as assigning values, reading input, and exporting variables. Understand the scope and syntax of variables in the Bourne shell.

  6. Variable Declaration and Assignment

    Learn how to declare and assign variables in Bash script for different data types, such as strings, numbers, arrays, and associative arrays. See practical examples of basic variable assignment, input from user, and output of variables.

  7. Introduction to Variables in Bash Scripting [An Ultimate Guide]

    Learn the basics of variables in bash script, including their types, declaration, assignment, and usage. Explore system-defined, user-defined, special, and environmental variables with examples and syntax.

  8. How to Set Variables in Bash: Shell Script Syntax Guide

    Learn how to set variables in Bash using the '=' operator and various techniques. Explore advanced topics such as environment variables, array variables, and alternative approaches to Bash variables.

  9. Shell Scripting

    Learn how to use shell variables in shell scripting, such as defining, accessing, unset, read-only, and different types of variables. See examples of echo command, read command, and other shell commands with variables.

  10. Assigning default values to shell variables with a single command in

    Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null. # The value of VARIABLE remains untouched.

  11. Variables in Bash/Shell Scripts and How To Use Them [Tutorial]

    Learn how to declare, use, and set variables in Bash and Shell scripts in Linux. See examples of string, integer, array, and function variables, and how to use declare command for typing.

  12. Using "${a:-b}" for variable assignment in scripts

    This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt. ${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  13. Bash Script: Set variable example

    Learn how to set and use variables in a Bash script on Linux. See examples of declaring, executing, and nesting variables, as well as reading user input and output.

  14. How to Use Variables in Shell Scripting

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

  15. Bash Variables

    Learn what a Bash variable is and how to use it in Linux scripts. Find out the types, characteristics, and applications of Bash variables with practical examples.

  16. Linux Bash: Multiple Variable Assignment

    Unfortunately, not all programming languages support the multiple variable assignment feature. Bash and shell script don't support this feature. Therefore, the assignment above won't work. However, we can achieve our goal in some other ways. Next, let's figure them out. 3. Using the read Command

  17. Bash Variables (Bash Reference Manual)

    When referenced, this variable expands to the name of the shell or shell script (identical to $0; See Special Parameters, for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0. If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset. BASH_CMDS ¶

  18. shell

    As an aside, all-caps variables are defined by POSIX for variable names with meaning to the operating system or shell itself, whereas names with at least one lowercase character are reserved for application use. Thus, consider using lowercase names for your own shell variables to avoid unintended conflicts (keeping in mind that setting a shell variable will overwrite any like-named environment ...

  19. How to build a conditional assignment in bash?

    90. If you want a way to define defaults in a shell script, use code like this: : ${VAR:="default"} Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default. This is related because this is my most common use case for that kind of logic. ;]

  20. bash

    1. As far as I know, bash unfortunately does not support constructs like associative arrays, which could be a possible solution, prior version 4. If the paths for the environments all look like the same, you could write it like this. #!/bin/sh. base_path="/tmp/in". dev_env="dev". simu_env="simu". run() {.