TecAdmin

Bash Assignment Operators (Shell Scripting)

In bash programming, assignment operators are like tools that let you give values to things. For example, you can tell the computer that “x equals 5” or “name equals tecadmin” . This way, whenever you talk about “x” or “name” later in your code, the computer knows exactly what you mean. It’s like labeling boxes in a storeroom so you know what’s inside each one without opening them.

In this article, we have split the assignment operator into four basic types. Let’s go over each type one by one with an example to make it easier to understand.

1. Standard Assignment Operator

In Bash programming, the standard assignment operator is the = symbol. It is used to assign the value on the right-hand side to the variable on the left-hand side. Make sure there are no spaces around the `=` operator.

Here is an quick example:

In this example, the variable `SHELL` is assigned the value “tecadmin” . If you use `echo $DOAMIN` , the output will be “tecadmin” .

2. Compound Assignment Operators

The compound assignment operators combination of performing some operation and then assign value to variable in a single operation. Basically it reduces line of code in your script and increase performance.

Please note that Bash only supports integer arithmetic natively. If you need to perform operations with floating-point numbers, you will need to use external tools like bc.

3. Read-only Assignment Operator

The readonly operator is used to make a variable’s value constant, which means the value assigned to the variable cannot be changed later. If you try to change the value of a readonly variable, Bash will give an error.

In the above example, PI is declared as a readonly variable and assigned a value of 3.14 . When we try to reassign the value 3.1415 to PI , Bash will give an error message: bash: PI: readonly variable .

4. Local Assignment Operator

The local operator is used within functions to create a local variable – a variable that can only be accessed within the function where it was declared.

In the above example, MY_VAR is declared as a local variable in the my_func function. When we call the function, it prints “I am local” . However, when we try to echo MY_VAR outside of the function, it prints nothing because MY_VAR is not accessible outside my_func .

Assignment operators are used a lot in programming. In shell scripting, they help with saving and changing data. By learning and using these operators well, you can make your scripts work better and faster. This article talked about the basic assignment operator, compound assignment operators, and special ones like readonly and local. Knowing how and when to use each type is important for getting really good for writing Bash scripts.

Related Posts

Shell Scripting Challenge 002! Guess the Output?

Shell Scripting Challenge 002! Guess the Output?

Shell Scripting Challenge - Day 1

Shell Scripting Challenge 001 | What is the output of following Script?

50 bash scripting examples (part-1).

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

Type above and press Enter to search. Press Esc to cancel.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Operator > Bash Logical Operators

Bash Logical Operators

Mohammad Shah Miran

Bash logical operators are essential components of shell scripting that enable users to create conditional expressions and make decisions based on the evaluation of conditions. These operators can be combined with various conditions to control the flow of Bash scripts and perform different actions based on specific criteria.

In this article, I will discuss the role of logical operators and their functionality in Bash script. So let’s move on!

Table of Contents

Basics of Logical Operators in Bash

In Bash scripting, logical operators can assess conditions and construct intricate expressions by merging two or more conditions. These operators enable users to determine whether a condition or a set of conditions holds true, granting the ability to manage the script’s execution flow effectively. In the following section, I will give you an overall demonstration of the types of logical operators in bash script.

Types of Logical Operators in Bash

In Bash scripting, logical operators are fundamental for making decisions and controlling the flow of commands based on conditions. They evaluate conditions to be either true or false and make a decision based on the result of the condition. The three primary logical operators are AND , OR , and NOT operators . Let’s have a syntax of each operator below.

  • AND Operator: The AND operator in Bash produces a true outcome solely when both assessed conditions are true. The syntax for the AND operator in Bash scripting is && .
  • OR Operator: The OR operator evaluates to true if at least one of the conditions it connects evaluates to true. The syntax for the OR operator in Bash scripting is || .
  • NOT Operator: The NOT operator in Bash scripting reverses the outcome of a condition. It is denoted by the !  syntax and is used to negate the result of a given condition.

3 Cases of Using Logical Operators in Bash Scripting

In the following section of this article, I will show you the practical cases of bash logical operators to give a sense of their functionality.

Case 01: Combining Conditions With Logical Operators

Combining logical operators can help check multiple conditions simultaneously. Following is an example where two logical AND operators and an echo command are used to display the output of the command.

This Bash script begins by assigning the variables grade to 5 and name to Bob. It then uses a conditional statement within double square brackets ‘[[‘ to check two conditions simultaneously. The first condition, $grade -ge 4  evaluates whether the grade variable is greater than or equal to 4 . The second condition, $name == "Bob" checks if the name variable equals Bob .

The && operator ensures that both conditions must be true for the subsequent command to execute. If both conditions are met, it echoes the message “Student name is Bob and Grade is Greater than 4” to the console.

Combining Conditions with Logical Operators

Case 02: Logical Operators in If-Else Statements

Logical operators can easily be implemented within if-else statement to perform conditional checking. Here’s such an example:

This Bash script starts by checking if the number of command-line arguments provided is less than 3 using the $# variable, which holds the number of arguments . If there are fewer than 3 arguments, it displays a usage message and exits . Then, it assigns the variables age , name , and is_student with the positional parameters $1, $2 and $3 respectively.

Next, it uses an if statement with double square brackets [[ … ]] to check multiple conditions. It verifies whether the age stored in the age variable is greater than 18 , whether the name variable contains the string “John”, and whether the is_student variable is set to true. If all these conditions are met, it prints the message “John is older than 18 and is a student.” Otherwise, it displays “John does not meet all the specified conditions.”

Logical Operators in if-else Statements

Case 03: Combining Multiple Boolean Operators in a Bash Script

Navigate through the script below to combine multiple Boolean (aka logical operators) operators &&, || and ! in Bash:

This Bash script initializes variables for age , name , and student status . It then uses an if statement with logical operators to check if Alice’s age is greater than or equal to 18 , her name is not Bob , and she is either a student or under 30 years old. If all these conditions are met, it prints that Alice is eligible; otherwise, it states that she does not meet the specified conditions.

Combining Multiple Boolean Operators in a Bash Script

5 Practical Examples of Using Logical Operators in Bash Scripting

Previously I showed 3 different scenarios to incorporate the logical operators in bash script. However, the following section will give 5 different examples by using the logical operator.

Example 01: Check if a Number is Within a Specific Range

Logical operators help in creating complex expressions by combining conditions. For instance, the objective of the following Bash script is to assess whether a given numerical value, provided as a command-line argument, falls within the specified range of 10 to 20 .

This Bash script takes a single command-line argument value and checks if it falls within the range of 10 to 20 using an if statement with the && logical operator. If the value is greater than 10 AND less than 20 , it prints “The value is within the range of 10 to 20.” Otherwise, it prints “The value is not within the range of 10 to 20.”

Check if a Number is within a Specific Range

Example 02: Check if a User is Either “root” or “admin” Using Boolean Operators

The OR operator is used to check if any of the condition is true within a conditional statement. For example, here’s a Bash script that determines whether a user , represented by the variable username , is either root or admin and ascertain if the user has administrative privileges on the system.

This Bash script begins by capturing a username provided as an argument when running the script. It proceeds to check two conditions using the if statement. First, it examines whether the effective user ID ( UID ) of the user executing the script is equal to 0 , which signifies the root user .

Second, it employs the sudo command to evaluate whether the specified username has sudo privileges. The grep -q part in this condition silences any output and checks if the pattern (ALL : ALL) exists in the sudo configuration, indicating sudo privileges. If either condition is true, the script prints a message declaring that the user possesses sudo privileges and is thus either the root user or an admin user. Conversely, if neither condition is met, it communicates that the username is neither the root user nor has sudo privileges.

 Check if a User is Either “root” or “admin” Using Boolean Operators

Example 03: Invert a Condition Using the “NOT” Operator

The NOT (!) operator reverses the condition within an if statement in Bash. Check out the following script to see the example of condition inversion:

This Bash script begins by defining a variable named file_to_check and assigns it the value test_file.txt . It then uses an if statement to check if the file specified by file_to_check exists in the current directory, utilizing the -e test operator within double square brackets. If the file does not exist, it outputs a message indicating that the file is not present. Conversely, if the file exists, it outputs a message confirming its existence.

Invert a Condition Using the NOT Operator-2

Example 04: Using of “NOT” and “AND” Logical Operators in a Single Line

To combine the NOT and AND operators in a single line, go through the script below:

The given bash code starts by prompting the user to enter their age and whether they have any voting disqualifications. It uses the read command to capture these inputs. Then, it uses an if statement to check if the user’s age is greater than or equal to 18 and if their response to disqualifications is not yes. If both conditions are met, it prints “Congratulations! You are eligible to vote.” Otherwise, it prints “Sorry, you are not eligible to vote at the moment.”

Using of OR and NOT Operator in a Single Line

Example 05: Using of “OR” and “NOT” Operator in a Single Line

Navigate through the following script to use the NOT and OR operators together in a single line:

The code begins by printing a message asking the user to provide their correct username and password for a greeting. The correct username and password are defined as “miran” and 1234 in the script. The script uses the read to prompt the user to enter their username and password . The -s flag with read is used for the password input to keep it hidden as the user types.

It then uses an if statement to check if the entered username and password match the correct ones. If either the username or password is incorrect, it prints “Login failed. Invalid username or password.” Otherwise, if both are correct, it prints “Login successful! Welcome, [username].”

Using of NOT and AND Logical Operators in a Single Line

In conclusion, Logical operators in bash scripting can play a vital role in assigning multiple conditions and making decisions based on them. In this article, I have demonstrated some different examples of logical operators in bash to convey its functionality. If you have any questions or queries related to this, feel free to comment below. I will get back to you soon. Till then, Happy Coding!

People Also Ask

What are logical operators in bash.

Logical operators in Bash include && ( AND ), || ( OR ), and ! ( NOT ). They are used to perform logical comparisons and control the flow of commands based on conditions.

What is the += operator in Bash?

In Bash, the += operator is a compound assignment operator that allows you to add ( concatenate ) a string or value to the end of an existing variable’s value. It’s commonly used for building or modifying strings dynamically in scripts.

What is binary operator in Bash?

A binary operator in Bash is an operator that works on two operands or values. It requires two values to perform an operation, such as addition , subtraction , comparison , or logical operations . Examples of binary operators in Bash include + for addition , – for subtraction , == for equality comparison , and && for logical AND operations .

What is the use of && in Bash?

In Bash, && is a logical operator used to execute the command on its right only if the command on its left succeeds (returns a zero exit status).

Related Articles

  • Boolean Variables “True False” and Logical Operators in Bash
  • Usage of Logical AND (&&) Operator in Bash Scripting
  • Usage of OR Operator in Bash Scripting [2 Cases]
  • Usages of NOT (!) Operator in Bash Scripting [4 Examples]

<< Go Back to Bash Operator | Bash Scripting Tutorial

Mohammad Shah Miran

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.

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

bash(1) — Linux manual page

Name         top, synopsis         top, copyright         top, description         top, options         top, arguments         top, invocation         top, definitions         top, reserved words         top, shell grammar         top, comments         top, quoting         top, parameters         top, expansion         top, redirection         top, aliases         top, functions         top, arithmetic evaluation         top, conditional expressions         top, simple command expansion         top, command execution         top, command execution environment         top, environment         top, exit status         top, signals         top, job control         top, prompting         top, readline         top, history         top, history expansion         top, shell builtin commands         top, shell compatibility mode         top, restricted shell         top, see also         top, files         top, authors         top, bug reports         top, bugs         top, colophon         top.

Pages that refer to this page: getopt(1) ,  intro(1) ,  kill(1) ,  pmdabash(1) ,  pv(1) ,  quilt(1) ,  systemctl(1) ,  systemd-notify(1) ,  systemd-run(1) ,  time(1) ,  setpgid(2) ,  getopt(3) ,  history(3) ,  readline(3) ,  strcmp(3) ,  termios(3) ,  ulimit(3) ,  core(5) ,  credentials(7) ,  environ(7) ,  suffixes(7) ,  time_namespaces(7) ,  cupsenable(8) ,  dpkg-fsys-usrunmess(8) ,  wg(8) ,  wg-quick(8)

Learn Scripting

Coding Knowledge Unveiled: Empower Yourself

Mastering Operators in Shell Scripting: A Comprehensive Guide

Shell scripting is a powerful tool for automating tasks and performing various operations on Unix-like operating systems. Operators play a fundamental role in shell scripts, allowing you to manipulate data, perform calculations, and make decisions. In this blog, we’ll delve into the world of operators in shell scripting, exploring their types, usage, and real-world applications.

Operators in Shell Scripting

Operators in shell scripting are symbols or special keywords that perform operations on variables, constants, and values. They allow you to work with data, make comparisons, and control the flow of your scripts. Shell scripting supports several types of operators:

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations in shell scripts. They include:

  • Addition (+): Adds two values.
  • Subtraction (-): Subtracts the second value from the first.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides the first value by the second.
  • Modulus (%): Computes the remainder of the division.
  • Exponentiation ( or ^):** Raises the first value to the power of the second (not available in all shells).

Here’s an example of using arithmetic operators in a shell script:

2. Comparison Operators

Comparison operators are used to compare values or expressions in shell scripts. They return a Boolean result (either true or false) based on the comparison. Common comparison operators include:

  • Equal to (==): Checks if two values are equal.
  • Not equal to (!=): Checks if two values are not equal.
  • Greater than (>): Checks if the first value is greater than the second.
  • Less than (<): Checks if the first value is less than the second.
  • Greater than or equal to (>=): Checks if the first value is greater than or equal to the second.
  • Less than or equal to (<=): Checks if the first value is less than or equal to the second.

Here’s an example of using comparison operators in a shell script:

3. Logical Operators

Logical operators are used to perform logical operations in shell scripts, especially within conditional statements. They include:

  • AND (&&): Returns true if both operands are true.
  • OR (||): Returns true if at least one operand is true.
  • NOT (!): Inverts the Boolean value of the operand.

Here’s an example of using logical operators in a shell script:

4. Assignment Operators

Assignment operators are used to assign values to variables in shell scripts. The basic assignment operator is = . However, there are also compound assignment operators that combine an operation with assignment, such as += , -= , *= , and /= .

Here’s an example of using assignment operators in a shell script:

5. String Operators

String operators are used for string manipulation in shell scripts. They include:

  • Concatenation (+=): Combines two strings.
  • Equality (==): Checks if two strings are equal.
  • Inequality (!=): Checks if two strings are not equal.
  • Length (strlen): Returns the length of a string.

Here’s an example of using string operators in a shell script:

Real-World Applications

Operators are essential in shell scripting and have numerous real-world applications:

  • Data Processing: Operators are used to manipulate data, perform calculations, and format output.
  • Conditionals: Comparison and logical operators enable you to create conditional statements for decision-making in scripts.
  • Looping: Operators play a crucial role in controlling loops, allowing you to set conditions for loop termination.
  • String Manipulation: String operators help in tasks like concatenating, splitting, and checking strings.
  • File Operations: Operators are used in shell scripts for file operations, such as checking file existence, permissions, and modification dates.
  • Script Automation: Operators facilitate automation by enabling scripts to make decisions and perform actions based on conditions.

Operators are the building blocks of shell scripting, enabling you to perform a wide range of tasks efficiently and effectively. By understanding and mastering the various types of operators, you can write more powerful and flexible shell scripts to automate tasks, manipulate data, and make intelligent decisions. Whether you’re a system administrator, developer, or data analyst, a solid grasp of shell scripting operators is a valuable skill in the world of Unix-like operating systems.

Leave a Reply Cancel reply

You must be logged in to post a comment.

A Complete Guide on How To Use Bash Arrays

The Bash array variables come in two flavors, the one-dimensional indexed arrays , and the associative arrays . The indexed arrays are sometimes called lists and the associative arrays are sometimes called dictionaries or hash tables . The support for Bash Arrays simplifies heavily how you can write your shell scripts to support more complex logic or to safely preserve field separation.

This guide covers the standard bash array operations and how to declare ( set ), append , iterate over ( loop ), check ( test ), access ( get ), and delete ( unset ) a value in an indexed bash array and an associative bash array . The detailed examples include how to sort and shuffle arrays.

👉 Many fixes and improvements have been made with Bash version 5, read more details with the post What’s New in GNU Bash 5?

Difference between Bash Indexed Arrays and Associative Arrays

How to declare a bash array.

Arrays in Bash are one-dimensional array variables. The declare shell builtin is used to declare array variables and give them attributes using the -a and -A options. Note that there is no upper limit (maximum) on the size (length) of a Bash array and the values in an Indexed Array and an Associative Array can be any strings or numbers, with the null string being a valid value.

👉 Remember that the null string is a zero-length string, which is an empty string. This is not to be confused with the bash null command which has a completely different meaning and purpose.

Bash Indexed Array (ordered lists)

You can create an Indexed Array on the fly in Bash using compound assignment or by using the builtin command declare . The += operator allows you to append a value to an indexed Bash array.

With the declare built-in command and the lowercase “ -a ” option, you would simply do the following:

Bash Associative Array (dictionaries, hash table, or key/value pair)

You cannot create an associative array on the fly in Bash. You can only use the declare built-in command with the uppercase “ -A ” option. The += operator allows you to append one or multiple key/value to an associative Bash array.

⚠️ Do not confuse -a (lowercase) with -A (uppercase). It would silently fail. Indeed, declaring an Indexed array will accept subscript but will ignore it and treat the rest of your declaration as an Indexed Array, not an Associative Array.
👉 Make sure to properly follow the array syntax and enclose the subscript in square brackets [] to avoid the " Bash Error: must use subscript when assigning associative array " .

When to use double quotes with Bash Arrays?

A great benefit of using Bash Arrays is to preserve field separation. Though, to keep that behavior, you must use double quotes as necessary. In absence of quoting, Bash will split the input into a list of words based on the $IFS value which by default contain spaces and tabs.

Array Operations

How to iterate over a bash array (loop).

As discussed above, you can access all the values of a Bash array using the * (asterisk) notation. Though, to iterate through all the array values you should use the @ (at) notation instead.

How to get the Key/Value pair of a Bash Array? (Obtain Keys or Indices)

When looping over a Bash array it’s often useful to access the keys of the array separately of the values. This can be done by using the ! (bang) notation.

How to get a Bash Array size? (Array length)

Another useful aspect of manipulating Bash Arrays is to be able to get the total count of all the elements in an array. You can get the length (i.e. size) of an Array variable with the # (hashtag) notation.

How to remove a key from a Bash Array or delete the full array? (delete)

The unset bash builtin command is used to unset (delete or remove) any values and attributes from a shell variable or function. This means that you can simply use it to delete a Bash array in full or only remove part of it by specifying the key. unset take the variable name as an argument, so don’t forget to remove the $ (dollar) sign in front of the variable name of your array. See the complete example below.

Detailed Examples & FAQ

How to shuffle the elements of an array in a shell script.

There are two reasonable options to shuffle the elements of a bash array in a shell script. First, you can either use the external command-line tool shuf that comes with the GNU coreutils, or sort -R in older coreutils versions. Second, you can use a native bash implementation with only shell builtin and a randomization function. Both methods presented below assume the use of an indexed array, it will not work with associative arrays.

The shuf command line generates random permutations from a file or the standard input. By using the -e option, shuf would treat each argument as a separate input line. Do not forget to use the double-quote otherwise elements with whitespaces will be split . Once the array is shuffled we can reassign its new value to the same variable.

How to sort the elements of an Array in a shell script?

How to get a subset of an array.

The shell parameter expansions works on arrays which means that you can use the substring Expansion ${string:<start>:<count>} notation to get a subset of an array in bash. Example: ${myArray[@]:2:3} .

The notation can be use with optional <start> and <count> parameters. The ${myArray[@]} notation is equivalent to ${myArray[@]:0} .

How to check if a Bash Array is empty?

How to check if a bash array contains a value.

In order to look for an exact match, your regex pattern needs to add extra space before and after the value like (^|[[:space:]])"VALUE"($|[[:space:]]) .

With the Bash Associative Arrays, you can extend the solution to test values with [[ -z "${myArray[$value]}" ]] .

How to store each line of a file into an indexed array?

The easiest and safest way to read a file into a bash array is to use the mapfile builtin which read lines from the standard input. When no array variable name is provided to the mapfile command, the input will be stored into the $MAPFILE variable. Note that the mapfile command will split by default on newlines character but will preserve it in the array values, you can remove the trailing delimiter using the -t option and change the delimiter using the -d option.

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.

Previous: Conditional Constructs , Up: Compound Commands   [ Contents ][ Index ]

3.2.5.3 Grouping Commands

Bash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream.

Placing a list of commands between parentheses forces the shell to create a subshell (see Command Execution Environment ), and each of the commands in list is executed in that subshell environment. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes.

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.

In addition to the creation of a subshell, there is a subtle difference between these two constructs due to historical reasons. The braces are reserved words, so they must be separated from the list by blank s or other shell metacharacters. The parentheses are operators, and are recognized as separate tokens by the shell even if they are not separated from the list by whitespace.

The exit status of both of these constructs is the exit status of list .

COMMENTS

  1. Linux Bash: Multiple Variable Assignment

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

  2. Using compound conditions in a Bash shell script

    In Bash, the double parentheses set up an arithmetic context (in which dollar signs are mostly optional, by the way) for a comparison (also used in for ((i=0; i<=10; i++)) and $(()) arithmetic expansion) and is used to distinguish the sequence from a set of single parentheses which creates a subshell. This, for example, executes the command ...

  3. Bash Assignment Operators (Shell Scripting)

    In bash programming, assignment operators are like tools that let you give values to things. For example, you can tell the computer that "x equals 5" or "name equals tecadmin". ... Compound Assignment Operators. The compound assignment operators combination of performing some operation and then assign value to variable in a single ...

  4. Compound Commands (Bash Reference Manual)

    Compound commands are the shell programming language constructs. Each construct begins with a reserved word or control operator and is terminated by a corresponding reserved word or operator. Any redirections (see Redirections) associated with a compound command apply to all commands within that compound command unless explicitly overridden. In ...

  5. Bash Conditional Expressions (Bash Reference Manual)

    6.4 Bash Conditional Expressions. Conditional expressions are used by the [[compound command (see Conditional Constructs) and the test and [builtin commands (see Bourne Shell Builtins).The test and [commands determine their behavior based on the number of arguments; see the descriptions of those commands for any other command-specific actions. ...

  6. Bash Logical Operators

    In Bash, the += operator is a compound assignment operator that allows you to add (concatenate) a string or value to the end of an existing variable's value. It's commonly used for building or modifying strings dynamically in scripts. What is binary operator in Bash? A binary operator in Bash is an operator that works on two operands or

  7. bash(1)

    BASH(1) General Commands Manual BASH(1) NAME top bash - GNU Bourne-Again SHell SYNOPSIS top bash [options ... The += operator will append to an array variable when assigning using the compound assignment syntax; see PARAMETERS above. Any element of an array may be referenced using ${name [subscript]}. The braces are required to avoid conflicts ...

  8. Mastering Operators in Shell Scripting: A Comprehensive Guide

    4. Assignment Operators. Assignment operators are used to assign values to variables in shell scripts. The basic assignment operator is =. However, there are also compound assignment operators that combine an operation with assignment, such as +=, -=, *=, and /=. Here's an example of using assignment operators in a shell script:

  9. Mastering Variable Assignment In Bash: Syntax, Manipulation, Scopes

    Understanding the basic syntax for assigning variables is crucial for writing effective Bash scripts. In this section, we will explore the different ways to assign values to variables in Bash. Using the equals sign (=) operator. The most common method of assigning a value to a variable in Bash is by using the equals sign (=) operator.

  10. A Complete Guide on How To Use Bash Arrays

    This guide covers the standard bash array operations and how to declare ( set ), append, iterate over ( loop ), check ( test ), access ( get ), and delete ( unset) a value in an indexed bash array and an associative bash array. The detailed examples include how to sort and shuffle arrays. 👉 Many fixes and improvements have been made with ...

  11. Bash Variables (Bash Reference Manual)

    Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0. If BASH_ARGV0 is unset, it loses its special properties, ... 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.

  12. bash

    The fact that assigning an array to a variable via array=(value1 ...) is called a compound assignment by the Bash Reference Manual for Arrays strongly suggests that it is special syntax and that I cannot simply create array literals by using the (value1 ...) syntax for the value to be substituted in a shell parameter expansion. While trying ...

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

  14. Bash Math Operations (Bash Arithmetic) Explained

    The preferable way to do math in Bash is to use shell arithmetic expansion. The built-in capability evaluates math expressions and returns the result. The syntax for arithmetic expansions is: $((expression)) The syntax consists of: Compound notation (()) which evaluates the expression. The variable operator $ to store the result.

  15. Arrays (Bash Reference Manual)

    Bash provides one-dimensional indexed and associative array variables. ... The '+=' operator will append to an array variable when assigning using the compound assignment syntax; see Shell Parameters above. Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell's ...

  16. Bash array appending element issue

    Array Compound Assignment Syntax. The form with parentheses allows you to insert one or more elements at a time, and is (arguably) easier to read. For example: ... This second example works because Bash arrays are zero-indexed, so the length of the array is also the next available index that should be assigned when appending. Share.

  17. Bash arrays: compound assignments fail

    $ sh test.sh SHELL=/bin/bash Single-quoted v: v[0]=(a b c) v[1]= v[2]= Double-quoted v: v[0]=(a b c) v[1]= v[2]= Unquoted v: v[0]=a v[1]=b v[2]=c If you quote the assignment, it becomes a simple variable assignment; a simple mistake to make that is easily overlooked.

  18. Command Grouping (Bash Reference Manual)

    3.2.5.3 Grouping Commands. Bash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream. Placing a list of commands between parentheses forces the shell ...

  19. Compound associative array variable assignment in Bash fails when read

    Was expecting that the array's compound keys-values assignment reading from variable or command substituion would work. P.S. I think Bash: set associative array from variable answers my issue. The easiest for me to comprhende answer was the eval statement put in double quotes, which seems to work for me. e.g. ... #!/usr/bin/env bash # Capture ...