How-To Geek

How to work with variables in bash.

Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables.

Hannah Stryker / How-To Geek

Quick Links

Variables 101, 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

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

Let's use all of our variables at once:

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

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

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

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.

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

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

Type the following to run the script:

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

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

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

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

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:

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

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

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

./script_one.sh

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

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"

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.

It's FOSS

  • Learn Bash Scripting

Bash Basics

  • Bash Basics Series #1: Create and Run Your First Bash Shell Script
  • Bash Basics Series #2: Using Variables in Bash
  • Bash Basics Series #3: Passing Arguments and Accepting User Inputs
  • Bash Basics Series #4: Arithmetic Operations
  • Bash Basics Series #5: Using Arrays in Bash

Bash Basics Series #6: Handling String Operations

  • Bash Basics Series #7: If Else Statement
  • Bash Basics Series #8: For, While and Until Loops
  • Bash Basics Series #9: Functions in Bash

In this chapter of the Bash Basics series, learn to perform various common string operations like extracting, replacing and deleting substrings.

In most programming languages, you'll find a string data type. A string is basically a group of characters.

Bash shell is different though. There is no separate data type for strings. Everything is a variable here.

But that doesn't mean that you cannot deal with strings in the same way you do in C and other programming languages.

Finding substrings, replacing substrings, joining strings and many more string operations are possible in Bash shell.

In this part of the Bash Basics Series, you'll learn the basic string manipulations.

Get string length in bash

Let's start with the simplest option. Which is to get the length of a string. It's quite simple:

Let's use it in an example.

Example of getting string length in bash

As you can see, the second example had two words in it but since it was in quotes, it was treated as a single word. Even the space is counted as a character.

Join strings in bash

The technical term is concatenation of strings, one of the simplest possible string operations in bash.

You just have to use the string variables one after another like this:

Can it go any simpler than this? I don't think so.

Let's see it with an example. Here is my example script named join.sh :

Here's a sample run of this script:

Join two strings in bash

Extract substring in bash

Let's say you have a big string with several characters and you want to extract part of it.

To extract a substring, you need to specify the main string, the starting position of the substring and the length of the substring in the following manner:

Here's an example:

Extracting substring in bash

Even if you specify the substring length greater than the string length, it will only go till the end of the string.

Replace substring in bash

Let's say you have a big string and you want to replace part of it with another string.

In that case, you use this kind of syntax:

Replace substring in bash

As you can see above, the word good was replaced with best. I saved the replaced string to the same string to change the original.

Delete substring in bash

Let's talk about removing substrings. Let's say you want to remove part of a string. In that case, just provide the substring to the main string like this:

If the substring is found, it will be deleted from the string.

Let's see this with an example.

Delete substring in bash

This goes without saying that if the substring is not found, it is not deleted. It won't result in an error.

🏋️ Exercise time

It's time for you to practice string manipulation with simple exercises.

Exercise 1 : Declare a string 'I am all wet'. Now change this string by replacing the word wet with set.

Exercise 2 : Create a string that saves phone numbers in the following format 112-123-1234 . Now, you have to delete all - .

The answers can be discussed in this dedicated thread in the Community.

string assignment in bash

That should give you some decent practice with strings in bash. In the next chapter, you'll learn about using if-else statements in bash .

string assignment in bash

Stay tuned.

On this page

  • Shell Scripting
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Batch Script - Iterating Over an Array
  • Bash Scripting - How to check If File Exists
  • Bash Concatenate String
  • Bash Scripting - Write Output of Bash Command into Log File
  • Bash Scripting - Bash Read Password without Echoing back
  • Bash Scripting - Split String
  • Bash Script - Working of Bash Variables
  • Bash Scripting - While Loop
  • Bash Scripting - For Loop
  • Bash Scripting - Array
  • Bash Script - Quotes and its types
  • Bash Scripting - How to Run Bash Scripting in Terminal
  • Bash Script - Write Hello World Program
  • Bash Scripting - String
  • Bash Scripting - Until Loop
  • Bash Scripting - Bash Echo Command
  • Bash Scripting - How to read a file line by line
  • Bash Script - Arithmetic Operators
  • Bash Script - Command Substitution

Bash Scripting – How to Initialize a String

Strings are quite crucial aspects of programming and scripting. We need to store the characters in some variables. In this article, we’ll see how to initialize strings in BASH.

Basic String Initialization

To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. 

string assignment in bash

This simple example initializes a string and prints the value using the “$” operator. The “#!/bin/usr/env bash” is the shebang, which makes the kernel realize which interpreter to be run when executing, in our case, it’s the BASH interpreter. We have assigned the string “a” a value of “Hello”. Also, it must be noted that there should not be any whitespace around the assignment operator otherwise it generates errors in the script.

Usage of Double and single Quotes in Strings

The double quotes or single quotes might not be significant but when it comes to using variables inside the string, we make use of double quotes to expand the value of the variable.

string assignment in bash

In the above example, if we don’t use double quotes in the “ greet” string, the value of the variable “ name” would not expand and the string will be displayed as it is.

string assignment in bash

As we can see the variable “ name” is not expanded to the value and it is displayed as it is when we use single quotes when we have initialized the string “ greet “. 

Please Login to comment...

  • Bash-Script
  • 10 Best Free Social Media Management and Marketing Apps for Android - 2024
  • 10 Best Customer Database Software of 2024
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]

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

Mohammad Shah Miran

Variables allow you to store and manipulate data within your script, making it easier to organize and access information. In Bash scripts , variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.

Key Takeaways

  • Getting Familiar With Different Types Of Variables.
  • Learning how to assign single or multiple bash variables.
  • Understanding the arithmetic operation in Bash Scripting.

Free Downloads

Local vs global variable assignment.

In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .

A. Local Variable Assignment

In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.

Here are some key characteristics of local variable assignment:

  • Local variables in bash are created within a function or a block of code.
  • By default, variables declared within a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables typically store temporary or intermediate values within a specific context.

Here is an example in Bash script.

In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.

B. Global Variable Assignment

In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.

Here are some key characteristics of global variable assignment:

  • Global variables in bash are declared outside of any function or block.
  • They are accessible throughout the entire script.
  • Any variable declared outside of a function or block is considered global by default.
  • Global variables can be accessed and modified from any script part, including within functions.

Here is an example in Bash script given in the context of a global variable .

It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.

Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .

8 Different Cases to Assign Variables in Bash Script

In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.

Case 01: Single Variable Assignment

To assign a value to a single variable in Bash script , you can use the following syntax:

However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

To assign a single value to a variable in Bash , you can go in the following manner:

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • single_variable.sh : Name of the file.

❸ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable :

  • chmod : changes the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • single_variable.sh : File name to which the permissions are being applied.

❻ Run the script by using the following command:

Single Variable Assignment

Case 02: Multi-Variable Assignment in a Single Line of a Bash Script

Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.

You can follow the steps of Case 01 , to save & make the script executable.

Script (multi_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, three variables x , y , and z are assigned values 1 , 2 , and 3 , respectively. The echo statements are used to print the values of each variable. Following that, two variables var1 and var2 are assigned values “ Hello ” and “ World “, respectively. The semicolon (;) separates the assignment statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.

Multi-Variable Assignment in a Single Line of a Bash Script

Case 03: Assigning Variables From Command-Line Arguments

In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.

Script (var_as_argument.sh) >

The provided Bash script starts with the shebang ( #!/bin/bash ) to use Bash shell. The script assigns the first command-line argument to the variable name , the second argument to age , and the third argument to city . The positional parameters $1 , $2 , and $3 , which represent the values passed as command-line arguments when executing the script. Then, the script uses echo statements to display the values of the assigned variables.

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :

However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.

Script (env_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.

Script (default_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.

Script (user_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.

Assigning Value by Taking Input from the User

Case 07: Using the “let” Command for Variable Assignment

In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .

Script (let_var_assign.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $()   syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.

Script (shell_command_var.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.

  • Difference: ?
  • Quotient: ?
  • Remainder: ?
  • Write a Bash script to find and display the name of the largest file using variables in a specified directory.

In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Variable Declaration and Assignment  | Bash Variables | Bash Scripting Tutorial

icon linux

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

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

Bash Array – How to Declare an Array of Strings in a Bash Script

Veronica Stork

Bash scripts give you a convenient way to automate command line tasks.

With Bash, you can do many of the same things you would do in other scripting or programming languages. You can create and use variables, execute loops, use conditional logic, and store data in arrays.

While the functionality may be very familiar, the syntax of Bash can be tricky. In this article, you will learn how to declare arrays and then how to use them in your code.

How to Declare an Array in Bash

Declaring an array in Bash is easy, but pay attention to the syntax. If you are used to programming in other languages, the code might look familiar, but there are subtle differences that are easy to miss.

To declare your array, follow these steps:

  • Give your array a name
  • Follow that variable name with an equal sign. The equal sign should not have any spaces around it
  • Enclose the array in parentheses (not brackets like in JavaScript)
  • Type your strings using quotes, but with no commas between them

Your array declaration will look something like this:

That's it! It's that simple.

How to Access an Array in Bash

There are a couple different ways to loop through your array. You can either loop through the elements themselves, or loop through the indices.

How to Loop Through Array Elements

To loop through the array elements, your code will need to look something like this:

To break that down: this is somewhat like using forEach in JavaScript. For each string (str) in the array (myArray), print that string.

The output of this loop looks like this:

Note : The @ symbol in the square brackets indicates that you are looping through all of the elements in the array. If you were to leave that out and just write for str in ${myArray} , only the first string in the array would be printed.

How to Loop Through Array Indices

Alternatively, you can loop through the indices of the array. This is like a for loop in JavaScript, and is useful for when you want to be able to access the index of each element.

To use this method, your code will need to look something like the following:

The output will look like this:

Note : The exclamation mark at the beginning of the myArray variable indicates that you are accessing the indices of the array and not the elements themselves. This can be confusing if you are used to the exclamation mark indicating negation, so pay careful attention to that.

Another note : Bash does not typically require curly braces for variables, but it does for arrays. So you will notice that when you reference an array, you do so with the syntax ${myArray} , but when you reference a string or number, you simply use a dollar sign: $i .

Bash scripts are useful for creating automated command line behavior, and arrays are a great tool that you can use to store multiple pieces of data.

Declaring and using them is not hard, but it is different from other languages, so pay close attention to avoid making mistakes.

Veronica is a librarian by trade with a longtime computer programming habit that she is currently working on turning into a career. She enjoys reading, cats, and programming in React.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

COMMENTS

  1. How to Manipulate Strings in Bash on Linux

    Creating and Working With String Variables. All we need to declare a variable and assign a string to it is to name the variable, use the equals sign. =. , and provide the string. If there are spaces in your string, wrap it in single or double-quotes. Make sure there is no whitespace on either side of the equals sign.

  2. String Operation in Bash Scripts: [Beginner's Guide]

    You can find the position (index) of a specific letter or word in a string. To demonstrate, let's first create a string named str as follows: str="Bash is Cool". Now you can get the specific position (index) of the substring cool. To accomplish that, use the expr command: kabary@handbook:~/scripts$ word="Cool".

  3. How to assign a string value to a variable over multiple lines while

    The solutions given by esuoxu and Mickaël Bucas are the common and more portable ways of doing this.. Here are a few bash solutions (some of which should also work in other shells, like zsh).Firstly with the += append operator (which works in a slightly different way for each of an integer variable, a regular variable and an array).. text="Lorem ipsum dolor sit amet, consectetur adipisicing ...

  4. How to Work with Variables in Bash

    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.

  5. String Manipulation in Bash

    Bash is a sh-compatible shell and command processor and string manipulation is one of the most common tasks to be done in a shell environment. In this tutorial, we'll learn how to operate on strings using Bash. 2. String Variable Declaration and Assignment

  6. How to Use String Variables in Bash Script? [4 Cases]

    The string is a powerful variable of the Bash script. To assign a string on a variable, follow the below syntax: variable_name="string" Here, I have discussed some cases related to the Bash string variables. Case 01: Print a String Variable Using Bash Script. You can store strings in the Bash script variables. In this example, I will develop a ...

  7. String Variables in Bash [Manipulation, Interpolation & Testing]

    Case 1: Assigning & Accessing String Variables in Bash. If you want to create a string variable, you need to assign a value to the variable like variable_name="value". And for accessing the variable you have to put a dollar sign ($) before the variable name. Following is the step-by-step procedure for assigning & accessing Bash string ...

  8. Bash String Operations

    Bash string operations refer to the handling of strings in a Bash script or shell environment. The string operations mainly indicate the operations that are done on the string but do not change or edit the string. Let's see some of the basic string operations.

  9. String Manipulation in Shell Scripting

    String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content to a variable and printing its content: In ...

  10. Bash Basics Series #6: Handling String Operations

    Bash Basics Series #6: Handling String Operations. In this chapter of the Bash Basics series, learn to perform various common string operations like extracting, replacing and deleting substrings. In most programming languages, you'll find a string data type. A string is basically a group of characters. Bash shell is different though.

  11. How to build a conditional assignment in bash?

    Sorted by: 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. ;] Share.

  12. Bash Scripting

    Output: This simple example initializes a string and prints the value using the "$" operator. The "#!/bin/usr/env bash" is the shebang, which makes the kernel realize which interpreter to be run when executing, in our case, it's the BASH interpreter. We have assigned the string "a" a value of "Hello". Also, it must be noted ...

  13. shell

    Bash String Manipulation and Assignment. Ask Question Asked 4 years, 11 months ago. Modified 4 years, 11 months ago. Viewed 979 times -1 How can I manipulate a string and then assign it to a variable? This string manipulation works as I want: echo ${dir:2:5} | sed 's/[.]$//'; ...

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

    Case 05: Default Value Assignment. In Bash, you can assign default values to variables using the ${variable:-default} syntax. Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset. Here's a script to learn how it works.

  15. Bash Concatenate String Variables

    String concatenation is just a fancy programming word for joining strings together by appending one string to the end of another string. In this article, we will explain how to concatenate strings in Bash. Concatenating Strings # The easiest way to concatenate multiple string variables is by simply placing them next to one another:

  16. How to Assign Default Value to a Variable Using Bash

    To test our methods, we'll use the echo command along with basic shell variable assignments. 2. Parameter Expansion of $ {param:-param} If a variable, x, is unset or is the null string, then $ {x:-default_value} expands to the default_value string. Importantly, no assignment to the x variable takes place, and the variable retains its original ...

  17. Bash Array

    Bash scripts give you a convenient way to automate command line tasks. With Bash, you can do many of the same things you would do in other scripting or programming languages. You can create and use variables, execute loops, use conditional logic, and store data in arrays. While the functionality may be very familiar, the syntax of Bash can be ...

  18. BASH- string assignment with a string name containing a variable

    1. Alternate solution: instead of trying to dynamically create a variable name, replace your individual varialbes pid0Aff, pid1Aff, etc with an array (e.g., pidAff ), and use pidCtr to index it. This should put you on the right track: #! /bin/bash. pidAff[0]='zero'.

  19. bash

    set -e exits the shell if a command has an "unanticipated" non-zero exit status. By "unanticipated", I mean it runs in a context where you aren't specifically looking at its exit status. false by itself, for instance, would exit the shell.false || true would not, since you are anticipating the non-zero exit status by specifying another command to run if the first fails.

  20. syntax

    @dutCh's answer shows that bash does have something similar to the "ternary operator" however in bash this is called the "conditional operator ... but it will give unpredictable results if you use it for string comparisons and assignments.... (( )) treats any/all strings as 0 - Peter.O. May 12, 2011 at 22:51. 12. This can also be written: a ...