TecAdmin

Using Assignment Operators in Shell Scripts

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?

What is the Difference Between ${} and $() in Bash

What is the Difference Between ${} and $() in Bash?

Shell Scripting Challenge - Day 1

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

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.

  • PHOENIXNAP HOME
  • Colocation Overview
  • Data Center as a Service Solutions for Digital Transformation
  • Hardware as a Service Flexible Hardware Leasing
  • Meet-Me Room The Interconnectivity Hub
  • Schedule a Tour Guided Virtual Data Center Tour
  • Data Center Locations Global Data Center Footprint
  • Platform Overview
  • Rancher Deployment One-Click Kubernetes Deployment
  • Intel Xeon E-2300 Entry-Level Servers
  • 4th Gen Intel Xeon Scalable CPUs Boost Data-Intensive Workloads
  • Alliances Technology Partnerships
  • Object Storage S3-Compatible Storage Solution
  • Dedicated Servers Overview
  • FlexServers Vertical CPU Scaling
  • Intel Xeon-E Servers Intel Xeon 2200 Microarchitecture
  • GPU Servers Servers with NVIDIA Tesla GPUs
  • Dedicated Servers vs. BMC Compare Popular Platforms
  • Promotions See Available Discounts
  • Buy Now See All Servers
  • Managed Private Cloud (MPC) Highly Customizable Cloud
  • Data Security Cloud Secure-By-Design Cloud
  • Hybrid Cloud Multi-Platform Environment
  • Edge Computing Globally Distributed Servers
  • Object Storage S3 API Compatible Storage Service
  • Bare Metal Cloud API-Driven Dedicated Servers
  • Alternative Cloud Provider Overcome Public Cloud Limitations
  • Backup Solutions Veeam-Powered Services
  • Disaster Recovery VMware, Veeam, Zerto
  • Veeam Cloud Connect Backup and Replication
  • Managed Backup for Microsoft 365 Veeam-Powered Service
  • Data Security Cloud Secure-by-Design Cloud
  • Encryption Management Platform (EMP) Cryptographic Key Management
  • Confidential Computing Data-in-Use Encryption
  • Ransomware Protection Data Protection and Availability
  • DDoS Protection Network Security Features
  • CONTACT SUPPORT
  • Network Overview Global Network Footprint
  • Network Locations U.S., Europe, APAC, LATAM
  • Speed Test Download Speed Test
  • Blog IT Tips and Tricks
  • Glossary IT Terms and Definitions
  • Resource Library Knowledge Resources
  • Events Let's Meet!
  • Newsroom Media Library
  • Developers Development Resources Portal
  • APIs Access Our Public APIs
  • GitHub Public Code Repositories
  • Search for:

Bash Math Operations (Bash Arithmetic) Explained

Home » DevOps and Development » Bash Math Operations (Bash Arithmetic) Explained

Introduction

Math and arithmetic operations are essential in Bash scripting. Various automation tasks require basic arithmetic operations, such as converting the  CPU temperature  to Fahrenheit. Implementing math operations in Bash is simple and very easy to learn.

This guide teaches you how to do basic math in Bash in various ways.

bash math bash arithmetic explained

Prerequisites

  • Access to the command line/terminal.
  • A text editor to code examples, such as nano or Vi/Vim .
  • Basic knowledge of Bash scripting .

Why Do You Need Math in Bash Scripting?

Although math is not the primary purpose of Bash scripting, knowing how to do essential calculations is helpful for various use cases.

Common use cases include:

  • Adding/subtracting/multiplying/dividing numbers.
  • Rounding numbers.
  • Incrementing and decrementing numbers.
  • Converting units.
  • Floating-point calculations.
  • Finding percentages.
  • Working with different number bases (binary, octal, or hexadecimal).

Depending on the automation task, basic math and arithmetic in Bash scripting help perform a quick calculation, yielding immediate results in the desired format.

Bash Math Commands and Methods

Some Linux commands allow performing basic and advanced calculations immediately. This section shows basic math examples with each method.

Arithmetic Expansion

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:

The syntax consists of:

  • Compound notation (()) which evaluates the expression.
  • The variable operator $ to store the result.

Note: The square bracket notation ( $[expression] ) also evaluates an arithmetic expression, and should be avoided since it is deprecated.

For example, add two numbers and echo the result:

bash arithmetic expansion addition terminal output

The arithmetic expansion notation is the preferred method when working with Bash scripts. The notation is often seen together with if statements and for loops in Bash .

awk Command

The awk command acts as a selector for pattern expressions. For example, to perform addition using the awk command, use the following example statement:

awk addition terminal output

For variables x = 2 and y = 3 , the output prints x + y = 5 to the console.

The bc command (short for b asic c alculator) is a command-line utility that renders the bc language. The program runs as an interactive program or takes standard input to perform arbitrary precision arithmetic.

Pipe an equation from standard input into the command to fetch results. For example:

bc addition terminal output

The output prints the calculation result.

The dc command (short for d esk c alculator) is a calculator utility that supports reverse Polish notation. The program takes standard input and supports unlimited precision arithmetic.

Pipe a standard input equation into the command to fetch the result. For example:

dc addition terminal output

The p in the equation sends the print signal to the dc command.

declare Command

The Bash declare command allows integer calculations. To use declare for calculations, add the -i option. For example:

Echo each variable to see the results:

declare addition terminal output

The output prints each variable to the console.

expr Command

The expr command is a legacy command line utility for evaluating integer arithmetic. An example expr command looks like the following:

expr addition terminal output

Separate numbers and the operation sign with spaces and run the command to see the calculation result.

factor Command

The  factor  command is a command-line utility that prints the factors for any positive integer, and the result factorizes into prime numbers.

For example, to print the factors of the number 100, run:

factor 100 terminal output

The output prints the factored number.

let Command

The Bash let command performs various arithmetic, bitwise and logical operations. The built-in command works only with integers. The following example demonstrates the let command syntax:

let addition terminal output

The output prints the results.

test Command

The test command in Linux evaluates conditional expressions and often pairs with the Bash if statement . There are two variations for the test syntax:

test comparison terminal output

Or alternatively:

test bracket comparison terminal output

The test command evaluates whether two is greater than ( -gt ) three. If the expression is true, the output is zero ( 0 ), or one ( 1 ) if false.

Bash Arithmetic Operators

Bash offers a wide range of arithmetic operators for various calculations and evaluations. The operators work with the let , declare , and arithmetic expansion.

Below is a quick reference table that describes Bash arithmetic operators and their functionality.

SyntaxDescription
, Pre and post-increment.
, Pre and post-decrement.
, , , Addition, subtraction, multiplication, division.
, (or )Modulo (remainder) and exponentiation.
, , Logical AND, OR, and negation.
, , , Bitwise AND, OR, XOR, and negation.
, , , Less than or equal to, less than, greater than, and greater than or equal to comparison operators.
, Equality and inequality comparison operators.
Assignment operator. Combines with other arithmetic operators.

How to Do Math in Bash

Bash offers different ways to perform math calculations depending on the type of problem.

Below are examples of some common problems which use Bash math functionalities or commands as a solution. Most examples use the Bash arithmetic expansion notation. The section also covers common Bash math errors and how to resolve them.

Math with Integers

The arithmetic expansion notation is the simplest to use and manipulate with when working with integers. For example, create an expression with variables and calculate the result immediately:

bash arithmetic expansion variables terminal output

To evaluate multiple expressions, use compound notation, store each calculation in a variable, and echo the result. For example:

bash multiple equations terminal output

When trying to divide, keep the following in mind:

1. Division by zero (0) is impossible and throws an error.

bash division by zero error terminal output

2. Bash arithmetic expansion does not support floating-point arithmetic. When attempting to divide in this case, the output shows zero (0).

non-integer result terminal output

The result of integer division must be an integer.

Incrementing and Decrementing

Bash arithmetic expansion uses C-style integer incrementing and decrementing . The operator for incrementing or decrementing is either before or after the variable, yielding different behavior.

If the operator is before the variable ( ++x or --x ), the increment or decrement happens before value assignment. To see how pre-incrementing works, run the following lines:

c-style pre-increment terminal output

The variable increments, and the new value is immediately available.

If the operator is after the variable ( x++ or x-- ), the increment or decrement happens after value assignment. To see how post-incrementing works, run the following:

c-style post-increment terminal output

The variable stays the same and increments in the following use.

Floating-point Arithmetic

Although Bash arithmetic expansion does not support floating-point arithmetic, there are other ways to perform such calculations. Below are four examples using commands or programming languages available on most Linux systems.

1. Using awk for up to 6 decimal places:

awk bash floating point arithmetic terminal output

2. Using bc with the -l flag for up to 20 decimal places:

bc -l floating point arithmetic terminal output

3. Using Perl for up to 20 decimal places:

perl floating point arithmetic terminal output

Perl often comes preinstalled in Linux systems.

4. Using printf and arithmetic expansion to convert a fraction to a decimal:

Precision dictates how many decimal places, whereas the multiplier is a power of ten. The number should be lower than the multiplier. Otherwise, the formula puts trailing zeros in the result.

For example, convert 1/3 to a decimal with precision two:

printf bash arithmetic expansion floating point terminal output

Avoid this method for precise calculations and use it only for a small number of decimal places.

Calculating a Percentage and Rounding

Below are two ways to calculate a percentage in Bash.

1. Use printf with arithmetic expansion.

For example, calculate what percent 40 is from 71:

printf percent calculation terminal output

The precision is limited to two decimal places, and the answer always rounds down.

2. Use awk with printf for better precision:

For instance, calculate how many percent is 40 from 71 with:

awk percent calculation terminal output

The answer rounds up if the third decimal place is higher than five, providing better accuracy.

Finding a Factorial in the Shell

To calculate a factorial for any number, use a recursive Bash function .

For small numbers, Bash arithmetic expansion works well:

To check the factorial for a number, use the following syntax:

bash arithmetic expansion factorial function terminal output

The method is slow and has limited precision (up to factorial 20).

For higher precision, faster results, and larger numbers, use the bc command. For example:

Replace <number> with the factorial number to calculate. For example, to find the factorial of 50, use:

bc factorial function terminal output

The output prints the calculation result to the terminal.

Creating a Bash Calculator Function

Create a simple Bash calculator function with the following code:

calculate bc function terminal output

The function takes user input and pipes the equation into the bc command.

Alternatively, to avoid using programs, use Bash arithmetic expansion in a function:

calculate bash arithmetic expansion function terminal output

Keep the arithmetic expansion limitations in mind. Floating-point arithmetic is not available with this function.

Save the function into the .bashrc file to always have the function available in the shell.

Using Different Arithmetic Bases

By default, Bash arithmetic expansion uses base ten numbers. To change the number base, use the following format:

Where base is any integer between two and 64.

For example, to do a binary (base 2) calculation, use:

bash binary math terminal output

Octal (base 8) calculations use a 0 prefix as an alias. For example:

bash octal math terminal output

Hexadecimal (base 16) calculations allow using 0x as a base prefix. For example:

bash hexadecimal math terminal output

The output prints the result in base ten for any calculation.

Convert Units

Create a simple Bash script to convert units:

1. Open a text editor, such as Vim, and create a convert.sh script. For example:

2. Paste the following code:

The program uses Bash read to take user input and calculates the conversion from feet to inches and from inches to feet.

3. Save the script and close:

4. Run the Bash script with:

convert.sh bash script terminal output

Enter a number and see the result. For different conversions, use appropriate conversion formulas.

Solving "bash error: value too great for base"

When working with different number bases, stay within the number base limits. For example, binary numbers use 0 and 1 to define numbers:

Attempting to use 2#2 as a number outputs an error:

bash value too great for base error terminal

The number is not the correct format for binary use. To resolve the error, convert the number to binary to perform the calculation correctly:

The binary number 10 is 2 in base ten.

Solving "syntax error: invalid arithmetic operator"

The Bash arithmetic expansion notation only works for integer calculations. Attempt to add two floating-point numbers, for example:

The command prints an error:

bash syntax error invalid arithmetic operator terminal output

To resolve the error, use regular integer arithmetic or a different method to calculate the equation.

Solving "bash error: integer expression expected"

When comparing two numbers, the test command requires integers. For example, try the following command:

The output prints an error:

bash integer expression expected error terminal

Resolve the error by comparing integer values.

Note: Learn about mathematical operations in Python by exploring two methods to calculate the power of a number in our guide Python Power Operator and Function .

You know how to do Bash arithmetic and various calculations through Bash scripting.

For more advanced scientific calculations, use Python together with SciPy , NumPy , and other libraries.

bash compound assignment

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.

> Linux >

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)

HTML rendering created 2024-06-26 by , author of .

For details of in-depth that I teach, look .

Hosting by .

Combine and Execute Multiple Linux Commands

Last updated: March 18, 2024

bash compound assignment

  • Administration

announcement - icon

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

>> Explore a clean Baeldung

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

1. Overview

In this tutorial, we’ll see the different ways in which we can combine and execute multiple Linux commands efficiently . We’ll be using Bash for our examples, so there could be slight differences with other shells.

2. Why Combine Multiple Commands?

Executing commands one after the other in a command line is a regular activity for a Linux administrator. But, by doing so, we may face the following issues:

  • The first command can take a long time to complete – one has to wait until then to run the second command
  • We may miss a particular command when multiple commands are run one-by-one
  • We may misspell a particular command, which may lead to unintended consequences
  • It’s time-consuming and annoying to run multiple commands one-by-one

To prevent such situations and obtain the expected result, we can combine and execute multiple commands in the command line .

3. Concatenate Commands With “;”

The “ ;” operator executes all commands regardless of whether the previous ones failed or not.

After logging into the server, we can execute the following commands:

  • Change to logs directory (using cd )
  • List the latest ten log files (using ls and head )
  • Print the disk usage of logs files (using du )
  • Print the disk usage of all file systems (using df )

Nevertheless, we can concatenate all of the above tasks in a single line using the “ ; “ operator:

However, we need to keep in mind that if one command in the command chain fails , the remaining commands will execute anyways. And this may produce unexpected outputs. 

4. Concatenate Commands Conditionally

The above approach is not suitable for all situations. Such as executing commands based on the success or failure of the previous one . In such cases, we can use one of the following approaches.

4.1. Concatenate Commands With “ && “

The “ &&”  or AND operator executes the second command only if the preceding command succeeds.

Let’s say we want to change to a new directory using the  cd command and echo some message related to the new directory. To do that, one option is to concatenate the commands with “ ; “ :

This works fine if the cd command is successful. However, if the cd command fails, for example, if we misspelled the folder name accidentally, the  echo command will be executed in the /home directory:

In our example, the second command is echo. It may print misleading messages but won’t do harm to the system. However, if the second command is a dangerous operation, for instance, rm -rf * , then the whole command becomes: “ cd someDir; rm -rf * “. If the cd command fails, the rm command will be executed in the current directory, which is /home in our example .  As a result, all contents of the home directory will be removed. This would be fatal.

To avoid this, we want the second command not to start at all if the first command fails . The solutions is replacing the “ ; “ operator with “ && “:

As we can see, this time, the echo command doesn’t start if the cd command fails.

4.2. Concatenate Commands With “||”

The “||” or OR operator executes the second command only if the precedent command returns an error.

Let’s assume we’re creating a new shell script to archive log files. Before executing a new shell script, we need to make it executable. Let’s see how we can achieve this using the “||” operator.

First, we’ll check if it is executable. If it’s not, we’ll make it executable using the chmod command:

In this example , the chmod command executes only if the file archive_logs.sh is not executable.

5. Group Commands

In Bash, we can use both “ { } ” and “( ) ” operators to group commands. 

In this section, we’ll address how to use them to group commands and understand the difference between them through examples. Also, we’ll discuss the everyday use-cases of grouping commands.

5.1. Grouping Commands Using “ { } “

The syntax to use curly braces “ { } ” to group commands is:

Note that the semicolon (or newline) following the command list is required.

Let’s see an example of grouping four commands using “ { } “:

5.2. Grouping Commands Using “ ( ) “

The syntax to use parentheses “ ( ) ” to group commands is quite similar, except that the semicolon following the command list is optional:

Let’s group the same commands using “ ( ) “:

5.3. The Difference Between “ { } ” and “ ( ) “

There is just one single difference between command grouping using “ { } ” and “ ( ) “:

  • { Commands; } : Commands execute in current shell
  • ( Commands ) : Commands will execute in a subshell

When we change variables in a subshell, the changes are not visible outside the subshell . Let’s see an example to understand the difference between the two grouping methods.

First, let’s group commands using “ { } “:

As the output above shows, we initialized a variable: VAR=”1″  and changed its value to “ 2″ in the group. The variable is updated outside the command group as well.

Secondly, let’s do the same test using “ ( ) “:

This time, the variable is changed in a subshell. Therefore, the changes will not affect the outer shell.

Let’s see another example of the  cd command:

In this example, the first output is straightforward. However, in the second output, why was the directory change in “ ( ) ” not kept?

This is because the cd command sets the environment variable $PWD , and the pwd command reads the variable $PWD . When the  cd command updated the variable $PWD  in a subshell, the change is not visible in the outer shell.

5.4. When Do We Need to Group Commands?

Primarily, we need to group commands in two scenarios:

  • Apply same redirections on a list of commands
  • Apply logical operators on a list of commands

When commands are grouped, redirections may be applied to the entire command list:

We’ve learned that we can use && and || to concatenate commands conditionally. With the command group, we can execute a list of commands when the condition is satisfied.

Let’s say, we attempt to ping a website to check if it is alive. Only if the ping command fails, we want to send an SMS to admin and write a log message. To achieve it, we can group the sendSMS command and the writeLog  command:

To simulate the execution, we’ll use echo commands to simulate the  sendSMS  and the writeLog commands, and let them always run successfully:

Now let’s do some tests with the command group:

With the command group, the entire command executes as we expected, no matter whether the ping command succeeded or failed.

Next, let’s see what will happen if we don’t group the  sendSMS  and writeLog commands:

As the output above shows, without grouping the sendSMS and writeLog commands, if the site is down, the whole command works as we expect.

However, if the  ping command succeeds, the  writeLog command is executed anyway. This isn’t what we want.

Therefore, grouping commands may help us solve some problems neatly.

6. Multiple Commands in Background

To execute a single command in the background mode, we can use the “ & ” operator. But to execute multiple commands in the background, we can use one of two ways:

  • Use “ & ” along with “ && “
  • Use “ & ” along with command group

Let’s say we have a shell script, let’s call it execute_backup_db.sh , that backs up the application database. We need to check how much time this shell script takes to complete. Let’s use the date command before and after the execution of the shell script to get the total execution time. This shell script may take a long time to complete.

So let’s run this in the background using the “ & “  operator and log the command output in a log file:

Using “ & “ with “ ; ” will only run the final date command in the background . But the first date command and the shell script run only in the foreground. Instead, to run all commands in background conditionally, let’s do:

To achieve the same with “ ; “, let’s use the “( )” operator:

7. Conclusion

In this tutorial, we saw the different ways in which we can combine and execute multiple commands in the command line efficiently.

Operator “ ; “ can be used if the execution of multiple commands is unconditional. Whereas operators “ && ” and “ || ” can be used if the execution of the command is based on the success or failure of the previous command.

Moreover, we addressed two ways to group commands and discussed the difference between them.

Also, we saw how we could execute multiple commands in the foreground and the background.

However, to regularly run multiple commands in a particular order, we may need to put all those commands in a shell script.

Stack Exchange Network

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

Q&A for work

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

Bash's conditional operator and assignment

Can we use bash's conditional operator with assignment operators after colon?

Bash reference manual explains the arithmetic operators as follows.

  • conditional operator expr ? expr : expr
  • assignment = *= /= %= += -= <<= >>= &= ^= |=

First, this code seems to work well:

But when I use assignment operators after : , I got 'attempted assignment to non-variable' error:

Why can we use only assignment operators before colon?

  • shell-script

Gilles 'SO- stop being evil''s user avatar

  • It may be fun to perform variable assignments using the conditional operator but it'd make your code highly unreadable. I'd prefer ((a)) && b=1 || c=1 –  devnull Commented Apr 27, 2014 at 8:34
  • @devnull I think the code's readability depends most upon who reads it. Still, it may be true what you say, but I've tested ternary operators in dash, zsh, sh , and bash and they all behave the same, despite their not being specified by POSIX. Your example only works in bash and zsh as far as I know. However, this is POSIX friendly: ( : ${a?} ) && b=1 || c=1 . I also find it far easier to read than either ternary or your own example. –  mikeserv Commented Apr 27, 2014 at 13:05

3 Answers 3

Bash parses your last command as

which should make clear why it does not work. Instead you have to use

celtschk's user avatar

This is called a ternary assignment expression. Here's a bit from another answer of mine:

You see, as you say, this is a conditional assignment operation. It depends upon conditions. The syntax works like this:

I don't believe you are using this correctly.

From wikipedia :

?: is used as follows: condition ? value_if_true : value_if_false

The condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value_if_true if condition is true, but value_if_false otherwise. Usually the two sub-expressions value_if_true and value_if_false must have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows:

variable = condition ? value_if_true : value_if_false

The ?: operator is similar to the way conditional expressions ( if-then-else constructs) work in functional programming languages, like Scheme, ML, and Haskell, since if-then-else forms an expression instead of a statement in those languages.

I think your specific problem is related to this:

As in the if-else construct only one of the expressions 'x' and 'y' are evaluated.

If you read through the above link on ternary expressions you'll see that evaluation is short-circuited so your assignment on the false side errors because 1 = true .

In any case, it doesn't matter too much because I don't think this does what you think it does.

Community's user avatar

  • As WP says, $(()) can only contain arithmetic expressions and therefore, a general ternary assignment doesn't exist in Bash. –  zakmck Commented Apr 10, 2023 at 18:49
  • @zakmck i think you should check again. try the code in the example. –  mikeserv Commented Sep 24, 2023 at 2:07
  • @mkeserv, I usually check before commenting, now your turn: Works: echo $((1==2 ? 1 : 0)). Works, but accidentally: echo $((1==1 ? 1 : NO)). Doesn't work, evaluates $NO to 0, returns 0, not 'NO': echo $((1==2 ? 1 : NO)). Error: $((1==2 ? 1 : 'NO')). Error, "A" and "B" are evaluated to 0, result is 1: echo $(("A" == "B" ? 1 : 0)). The problem is $((x ? y : z)) is valid for numerical expressions only. Bash 5.1.8(1) –  zakmck Commented Sep 24, 2023 at 15:29
  • you cant assign to a number. the assigned variable has to be the first in the list. $((no?1:2)) and of course the ternary is valid for mumericals only; its arithmetic. –  mikeserv Commented Sep 24, 2023 at 21:10
  • the point is $(( ? : )) works when returning numbers only and the OP probably wants to know if such a ternary operator exists in general (as other say, it doesn't). –  zakmck Commented Sep 25, 2023 at 21:37

Ternary operators return a value based on a test. They are not used for branching.

Here's one way to get a pseudo-ternary operator for bash (note the back-ticks):

$result=`[ < condition > ] && echo "true-result" || echo "false-result" `

$ a= $ c=`[ $a ] && echo 1 || echo 0` $ echo $c 0 $ a=5 $ c=`[ $a ] && echo 1 || echo 0` $ echo $c 1

bearvarine's user avatar

You must log in to answer this question.

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

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...

Hot Network Questions

  • Manhwa where the (female) main character can see how and when someone will die
  • Equation of Time (derivation Analemma)
  • Why Pythagorean theorem is all about 2?
  • How to prove that the Greek cross tiles the plane?
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • Proper use of voices in more complicated melodies
  • Why would the absence of Chalmers' 'consciousness' make p-zombie world 'inconceivable'?
  • Is it possible to draw this picture without lifting the pen? (I actually want to hang string lights this way in a gazebo without doubling up)
  • How many minutes the Apollo astronauts had to wait from splashdown until the first frogmen touched the CM?
  • Twists of elliptic curves
  • How to reply to a revise and resubmit review, saying is all good?
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?
  • Does Rom.8.11 teach sanctification, or glorification?
  • In Photoshop, when saving as PNG, why is the size of my output file bigger when I have more invisible layers in the original file?
  • Why were there so many OSes that had the name "DOS" in them?
  • How much better is using quad trees than simple relational database for storing location data?
  • Why does Sfas Emes start his commentary on Parshat Noach by saying he doesn't know it? Is the translation faulty?
  • Why did early ASCII have ← and ↑ but not ↓ or →?
  • Browse a web page through SSH? (Need to access router web interface remotely, but only have SSH access to a different device on LAN)
  • Keyboard shortcuts for running last command with changes?
  • How can I send instance attributes from Geometry Nodes to Shading Editor?
  • Why is resonance such a widespread phenomenon?
  • "Famous award" - "on ships"
  • Have metal ships ever used ramming as a regular tactic?

bash compound assignment

Bash Shell Scripting/Shell Arithmetic


Arithmetic expressions in Bash are closely modeled on those in C, so they are very similar to those in other C-derived languages, such as C++, Java, Perl, JavaScript, C#, and PHP. One major difference is that Bash only supports integer arithmetic (whole numbers), not floating-point arithmetic (decimals and fractions); something like 3 + 4 means what you'd expect (7), but something like 3.4 + 4.5 is a syntax error. Something like 13 / 5 is fine, but performs integer division, so evaluates to 2 rather than to 2.6.

  • 1 Arithmetic expansion
  • 2 expr (deprecated)
  • 3 Numeric operators
  • 4 Referring to variables
  • 5 Assigning to variables
  • 6 Arithmetic expressions as their own commands
  • 7 The comma operator
  • 8 Comparison, Boolean, and conditional operators
  • 9 Arithmetic for-loops
  • 10 Bitwise operators
  • 11 Integer literals
  • 12 Integer variables
  • 13 Non-integer arithmetic

Arithmetic expansion

Perhaps the most common way to use arithmetic expressions is in arithmetic expansion , where the result of an arithmetic expression is used as an argument to a command. Arithmetic expansion is denoted $(( … )) . For example, this command:

prints 19 .

expr (deprecated)

Another way to use arithmetic expressions is using the Unix program "expr", which was popular before Bash supported math. [ 1 ] Similar to Arithmetic expansion, this command:

prints 19 . Note that using "expr" requires an escape character "\" before the multiplication operator "*" and parentheses. Further note the spaces between each operator symbol, including the parentheses.

Numeric operators

In addition to the familiar notations + (addition) and - (subtraction), arithmetic expressions also support * (multiplication), / (integer division, described above), % (modulo division, the "remainder" operation; for example, 11 divided by 5 is 2 remainder 1, so 11 % 5 is 1 ), and ** ("exponentiation", i.e. involution; for example, 2 4  = 16, so 2 ** 4 is 16 ).

The operators + and - , in addition to their "binary" (two-operand) senses of "addition" and "subtraction", have "unary" (one-operand) senses of "positive" and "negative". Unary + has basically no effect; unary - inverts the sign of its operand. For example, -(3*4) evaluates to -12 , and -(-(3*4)) evaluates to 12 .

Referring to variables

Inside an arithmetic expression, shell variables can be referred to directly, without using variable expansion (that is, without the dollar sign $ ). For example, this:

prints 35 . (Note that i is evaluated first, producing 5, and then it's multiplied by 7. If we had written $i rather than i , mere string substitution would have been performed; 7 * 2+3 equals 14 + 3, that is, 17 — probably not what we want.)

The previous example shown using "expr":

prints 35 .

Assigning to variables

Shell variables can also be assigned to within an arithmetic expression. The notation for this is similar to that of regular variable assignment, but is much more flexible. For example, the previous example could be rewritten like this:

except that this sets $i to 5 rather than to 2+3 . Note that, although arithmetic expansion looks a bit like command substitution, it is not executed in a subshell; this command actually sets $i to 5 , and later commands can use the new value. (The parentheses inside the arithmetic expression are just the normal mathematical use of parentheses to control the order of operations.)

In addition to the simple assignment operator = , Bash also supports compound operators such as += , -= , *= , /= , and %= , which perform an operation followed by an assignment. For example, (( i *= 2 + 3 )) is equivalent to (( i = i * (2 + 3) )) . In each case, the expression as a whole evaluates to the new value of the variable; for example, if $i is 4 , then (( j = i *= 3 )) sets both $i and $j to 12 .

Lastly, Bash supports increment and decrement operators. The increment operator ++ increases a variable's value by 1; if it precedes the variable-name (as the "pre-increment" operator), then the expression evaluates to the variable's new value, and if it follows the variable-name (as the "post-increment" operator), then the expression evaluates to the variable's old value. For example, if $i is 4 , then (( j = ++i )) sets both $i and $j to 5 , while (( j = i++ )) sets $i to 5 and $j to 4 . The decrement operator -- is exactly the same, except that it decreases the variable's value by 1. Pre-decrement and post-decrement are completely analogous to pre-increment and post-increment.

Arithmetic expressions as their own commands

A command can consist entirely of an arithmetic expression, using either of the following syntaxes:

Either of these commands will set $i to 5 . Both styles of command return an exit status of zero ("successful" or "true") if the expression evaluates to a non-zero value, and an exit status of one ("failure" or "false") if the expression evaluates to zero. For example, this:

will print this:

The reason for this counterintuitive behavior is that in C, zero means "false" and non-zero values (especially one) mean "true". Bash maintains that legacy inside arithmetic expressions, then translates it into the usual Bash convention at the end.

The comma operator

Arithmetic expressions can contain multiple sub-expressions separated by commas , . The result of the last sub-expression becomes the overall value of the full expression. For example, this:

sets $i to 2 , sets $j to 4 , and prints 8 .

The let built-in actually supports multiple expressions directly without needing a comma; therefore, the following three commands are equivalent:

Comparison, Boolean, and conditional operators

Arithmetic expressions support the integer comparison operators < , > , <= (meaning ≤), >= (meaning ≥), == (meaning =), and != (meaning ≠). Each evaluates to 1 for "true" or 0 for "false".

They also support the Boolean operators && ("and"), which evaluates to 0 if either of its operands is zero, and to 1 otherwise; || ("or"), which evaluates to 1 if either of its operands is nonzero, and to 0 otherwise; and ! ("not"), which evaluates to 1 if its operand is zero, and to 0 otherwise. Aside from their use of zero to mean "false" and nonzero values to mean "true", these are just like the operators && , || , and ! that we've seen outside arithmetic expressions. Like those operators, these are "short-cutting" operators that do not evaluate their second argument if their first argument is enough to determine a result. For example, (( ( i = 0 ) && ( j = 2 ) )) will not evaluate the ( j = 2 ) part, and therefore will not set $j to 2 , because the left operand of && is zero ("false").

And they support the conditional operator b  ? e1  : e2 . This operator evaluates e1 , and returns its result, if b is nonzero; otherwise, it evaluates e2 and returns its result.

These operators can be combined in complex ways:

Arithmetic for-loops

Above, we saw one style of for-loop, that looked like this:

Bash also supports another style, modeled on the for-loops of C and related languages, using shell arithmetic:

This for-loop uses three separate arithmetic expressions, separated by semicolons ; (and not commas , — these are completely separate expressions, not just sub-expressions). The first is an initialization expression, run before the loop begins. The second is a test expression; it is evaluated before every potential loop iteration (including the first), and if it evaluates to zero ("false"), then the loop exits. The third is a counting expression; it is evaluated at the end of each loop iteration. In other words, this for-loop is exactly equivalent to this while-loop:

but, once you get used to the syntax, it makes it more clear what is going on.

Bitwise operators

In addition to regular arithmetic and Boolean operators, Bash also offers "bitwise" operators, meaning operators that operate on integers qua bit-strings rather than qua integers. If you are not already familiar with this concept, you can safely ignore these.

Just as in C, the bitwise operators are & (bitwise "and"), | (bitwise "or"), ^ (bitwise "exclusive or"), ~ (bitwise "not"), << (bitwise left-shift), and >> (bitwise right-shift), as well as &= and |= and ^= (which include assignment, just like += ).

Integer literals

An integer constant is expressed as an integer literal . We have already seen many of these; 34 , for example, is an integer literal denoting the number 34. All of our examples have been decimal (base ten) integer literals, which is the default; but in fact, literals may be expressed in any base in the range 2–64, using the notation base # value (with the base itself being expressed in base-ten). For example, this:

will print 12 six times. (Note that this notation only affects how an integer literal is interpreted. The result of the arithmetic expansion is still expressed in base ten, regardless.)

For bases 11 through 36, the English letters A through Z are used for digit-values 10 through 35. This is not case-sensitive. For bases 37 through 64, however, it is specifically the lowercase English letters that are used for digit-values 10 through 35, with the uppercase letters being used for digit-values 36 through 61, the at-sign @ being used for digit-value 62, and the underscore _ being used for digit-value 63. For example, 64#@A3 denotes 256259 ( 62 × 64 2 + 36 × 64 + 3 ).

There are also two special notations: prefixing a literal with 0 indicates base-eight (octal), and prefixing it with 0x or 0X indicates base-sixteen (hexadecimal). For example, 030 is equivalent to 8#30 , and 0x6F is equivalent to 16#6F .

Integer variables

A variable may be declared as an integer variable — that is, its "integer attribute" may be "set" — by using this syntax:

After running the above command, any subsequent assignments to n will automatically cause the right-hand side to be interpreted as an arithmetic expression. For example, this:

is more or less equivalent to this:

except that the first version's declare -i n will continue to affect later assignments as well.

In the first version, note the use of quotes around the right-hand side of the assignment. Had we written n=2 + 3 > 4 , it would have meant "run the command + with the argument 3 , passing in the environment variable n set to 2 , and redirecting standard output into the file 4 "; which is to say, setting a variable's integer attribute doesn't affect the overall parsing of assignment statements, but merely controls the interpretation of the value that is finally assigned to the variable.

We can "unset" a variable's integer attribute, turning off this behavior, by using the opposite command:

The declare built-in command has a number of other uses as well: there are a few other attributes a variable can have, and declare has a few other features besides turning attributes on and off. In addition, a few of its properties bear note:

  • As with local and export , the argument can be a variable assignment; for example, declare -i n = 2 +3 sets $n 's integer attribute and sets it to 5 .
  • As with local and export , multiple variables (and/or assignments) can be specified at once; for example, declare -i m n sets both $m 's integer attribute and $n 's.
  • When used inside a function, declare implicitly localizes the variable (unless the variable is already local), which also has the effect of locally unsetting it (unless the assignment syntax is used).

Non-integer arithmetic

As mentioned above, Bash shell arithmetic only supports integer arithmetic. However, external programs can often be used to obtain similar functionality for non-integer values. In particular, the common Unix utility bc is often used for this. The following command:

prints 5.6 . Needless to say, since bc is not so tightly integrated with Bash as shell arithmetic is, it is not as convenient; for example, something like this:

would, to support non-integers, become something like this:

Part of this is because we can no longer use an arithmetic for-loop; part of it is because referring to variables and assigning to variables is trickier now (since bc is not aware of the shell's variables, only its own, unrelated ones); and part of it is because bc communicates with the shell only via input and output.

  • ↑ http://www.sal.ksu.edu/faculty/tim/unix_sg/bash/math.html

bash compound assignment

  • Book:Bash Shell Scripting
  • Pages using deprecated enclose attributes

Navigation menu

Next: Grouping Commands , Previous: Looping Constructs , Up: Compound Commands   [ Contents ][ Index ]

3.2.5.2 Conditional Constructs

The syntax of the if command is:

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘ else alternate-consequents ’ is present, and the final command in the final if or elif clause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

The syntax of the case command is:

case will selectively execute the command-list corresponding to the first pattern that matches word . The match is performed according to the rules described below in Pattern Matching . If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters. The ‘ | ’ is used to separate multiple patterns, and the ‘ ) ’ operator terminates a pattern list. A list of patterns and an associated command-list is known as a clause .

Each clause must be terminated with ‘ ;; ’, ‘ ;& ’, or ‘ ;;& ’. The word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal (see Shell Parameter Expansion ) before matching is attempted. Each pattern undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, process substitution, and quote removal.

There may be an arbitrary number of case clauses, each terminated by a ‘ ;; ’, ‘ ;& ’, or ‘ ;;& ’. The first pattern that matches determines the command-list that is executed. It’s a common idiom to use ‘ * ’ as the final pattern to define the default case, since that pattern will always match.

Here is an example using case in a script that could be used to describe one interesting feature of an animal:

If the ‘ ;; ’ operator is used, no subsequent matches are attempted after the first pattern match. Using ‘ ;& ’ in place of ‘ ;; ’ causes execution to continue with the command-list associated with the next clause, if any. Using ‘ ;;& ’ in place of ‘ ;; ’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match, continuing the case statement execution as if the pattern list had not matched.

The return status is zero if no pattern is matched. Otherwise, the return status is the exit status of the command-list executed.

The select construct allows the easy generation of menus. It has almost the same syntax as the for command:

The list of words following in is expanded, generating a list of items, and the set of expanded words is printed on the standard error output stream, each preceded by a number. If the ‘ in words ’ is omitted, the positional parameters are printed, as if ‘ in "$@" ’ had been specified. select then displays the PS3 prompt and reads a line from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the select command completes and returns 1. Any other value read causes name to be set to null. The line read is saved in the variable REPLY .

The commands are executed after each selection until a break command is executed, at which point the select command completes.

Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected.

The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic ). The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially are removed. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.

Return a status of 0 or 1 depending on the evaluation of the conditional expression expression . Expressions are composed of the primaries described below in Bash Conditional Expressions . The words between the [[ and ]] do not undergo word splitting and filename expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal on those words (the expansions that would occur if the words were enclosed in double quotes). Conditional operators such as ‘ -f ’ must be unquoted to be recognized as primaries.

When used with [[ , the ‘ < ’ and ‘ > ’ operators sort lexicographically using the current locale.

When the ‘ == ’ and ‘ != ’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching , as if the extglob shell option were enabled. The ‘ = ’ operator is identical to ‘ == ’. If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (‘ == ’) or does not match (‘ != ’) the pattern, and 1 otherwise.

If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning.

An additional binary operator, ‘ =~ ’, is available, with the same precedence as ‘ == ’ and ‘ != ’. When you use ‘ =~ ’, the string to the right of the operator is considered a POSIX extended regular expression pattern and matched accordingly (using the POSIX regcomp and regexec interfaces usually described in regex (3)). The return value is 0 if the string matches the pattern, and 1 if it does not. If the regular expression is syntactically incorrect, the conditional expression returns 2. If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters.

You can quote any part of the pattern to force the quoted portion to be matched literally instead of as a regular expression (see above). If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched literally.

The pattern will match if it matches any part of the string. If you want to force the pattern to match the entire string, anchor the pattern using the ‘ ^ ’ and ‘ $ ’ regular expression operators.

For example, the following will match a line (stored in the shell variable line ) if there is a sequence of characters anywhere in the value consisting of any number, including zero, of characters in the space character class, immediately followed by zero or one instances of ‘ a ’, then a ‘ b ’:

That means values for line like ‘ aab ’, ‘ aaaaaab ’, ‘ xaby ’, and ‘ ab ’ will all match, as will a line containing a ‘ b ’ anywhere in its value.

If you want to match a character that’s special to the regular expression grammar (‘ ^$|[]()\.*+? ’), it has to be quoted to remove its special meaning. This means that in the pattern ‘ xxx.txt ’, the ‘ . ’ matches any character in the string (its usual regular expression meaning), but in the pattern ‘ "xxx.txt" ’, it can only match a literal ‘ . ’.

Likewise, if you want to include a character in your pattern that has a special meaning to the regular expression grammar, you must make sure it’s not quoted. If you want to anchor a pattern at the beginning or end of the string, for instance, you cannot quote the ‘ ^ ’ or ‘ $ ’ characters using any form of shell quoting.

If you want to match ‘ initial string ’ at the start of a line, the following will work:

but this will not:

because in the second example the ‘ ^ ’ is quoted and doesn’t have its usual special meaning.

It is sometimes difficult to specify a regular expression properly without using quotes, or to keep track of the quoting used by regular expressions while paying attention to shell quoting and the shell’s quote removal. Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. For example, the following is equivalent to the pattern used above:

Shell programmers should take special care with backslashes, since backslashes are used by both the shell and regular expressions to remove the special meaning from the following character. This means that after the shell’s word expansions complete (see Shell Expansions ), any backslashes remaining in parts of the pattern that were originally not quoted can remove the special meaning of pattern characters. If any part of the pattern is quoted, the shell does its best to ensure that the regular expression treats those remaining backslashes as literal, if they appeared in a quoted portion.

The following two sets of commands are not equivalent:

The first two matches will succeed, but the second two will not, because in the second two the backslash will be part of the pattern to be matched. In the first two examples, the pattern passed to the regular expression parser is ‘ \. ’. The backslash removes the special meaning from ‘ . ’, so the literal ‘ . ’ matches. In the second two examples, the pattern passed to the regular expression parser has the backslash quoted (e.g., ‘ \\\. ’), which will not match the string, since it does not contain a backslash. If the string in the first examples were anything other than ‘ . ’, say ‘ a ’, the pattern would not match, because the quoted ‘ . ’ in the pattern loses its special meaning of matching any single character.

Bracket expressions in regular expressions can be sources of errors as well, since characters that are normally special in regular expressions lose their special meanings between brackets. However, you can use bracket expressions to match special pattern characters without quoting them, so they are sometimes useful for this purpose.

Though it might seem like a strange way to write it, the following pattern will match a ‘ . ’ in the string:

The shell performs any word expansions before passing the pattern to the regular expression functions, so you can assume that the shell’s quoting takes precedence. As noted above, the regular expression parser will interpret any unquoted backslashes remaining in the pattern after shell expansion according to its own rules. The intention is to avoid making shell programmers quote things twice as much as possible, so shell quoting should be sufficient to quote special pattern characters where that’s necessary.

The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the n th parenthesized subexpression.

Bash sets BASH_REMATCH in the global scope; declaring it as a local variable will lead to unexpected results.

Expressions may be combined using the following operators, listed in decreasing order of precedence:

Returns the value of expression . This may be used to override the normal precedence of operators.

True if expression is false.

True if both expression1 and expression2 are true.

True if either expression1 or expression2 is true.

The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Bash arrays: compound assignments fail

I have no idea why the compound array initialization does not work for me.

minimal example:

with 2 additional blank lines.

Fieldwise initialization works:

I have tried every possible combination of braces, quotes and "declare -a".

Could it be related to my bash version? I'm running version 4.1.2(1).

Artjom B.'s user avatar

  • Can't reproduce on bash 4.3.11. Both cases output foo bar foobar on separate lines. –  user000001 Commented Aug 5, 2014 at 9:19
  • What's the output of MINRADIUS=( 'foo' 'bar' 'foobar' ); printf '(%s)\n' "${MINRADIUS[@]}" ? –  konsolebox Commented Aug 5, 2014 at 10:55
  • 1 Can you try chmod +x test.sh and then ./test.sh ? Or bash test.sh ? Because sh can point to something different than bash. –  karolba Commented Aug 5, 2014 at 11:09

3 Answers 3

The problem is, you are not using bash. Shebang doesn't matter if you run your script throught sh . Try bash instead.

karolba's user avatar

I tried the below code and its working fine for me. Using bash 3.2.39(1)-release

Output for this was

For me with your code it was giving an error

Vishal R's user avatar

  • still giving me (foo bar foobar) :( –  Dolan Commented Aug 5, 2014 at 9:34

I would suspect there is some quoting going on in your first example using compound assignments. Using this modified test script:

I get the following output:

If you quote the assignment, it becomes a simple variable assignment; a simple mistake to make that is easily overlooked.

Go Dan's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • zsh completion - ignore executable files with no dot in the name
  • Why is steaming food faster than boiling it?
  • How can I send instance attributes from Geometry Nodes to Shading Editor?
  • What are the pros and cons of the classic portfolio by Wealthfront?
  • How to avoid bringing paper silverfish home from a vacation place?
  • Have metal ships ever used ramming as a regular tactic?
  • Should I change advisors because mine doesn't object to publishing at MDPI?
  • Does SpaceX Starship have significant methane emissions?
  • Why Pythagorean theorem is all about 2?
  • Movie where a young director's student film gets made (badly) by a major studio
  • Definition of annuity
  • Is it feasible to create an online platform to effectively teach college-level math (abstract algebra, real analysis, etc.)?
  • mmrm R package : No optimizer led to a successful model fit
  • "Famous award" - "on ships"
  • Why did early ASCII have ← and ↑ but not ↓ or →?
  • VBA: Efficiently Organise Data with Missing Values to Achieve Minimum Number of Tables
  • Should tiny dimension tables be considered for row or page compression on servers with ample CPU room?
  • Tire schrader core replacement without deflation
  • Difference between 2 version numbers from `adb --version`
  • How to expand argument in the Expl3 command \str_if_eq?
  • Does carbon fiber wings need wing spar?
  • Was Willy Wonka correct when he accused Charlie of stealing Fizzy Lifting Drinks?
  • The meaning of an implication in an existential quantifier
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?

bash compound assignment

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. Using Assignment Operators in Shell Scripts

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

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

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

  8. bash(1)

    Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0. If BASH_ARGV0 is ... 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 with ...

  9. Combine and Execute Multiple Linux Commands

    It's time-consuming and annoying to run multiple commands one-by-one. To prevent such situations and obtain the expected result, we can combine and execute multiple commands in the command line. 3. Concatenate Commands With ";". The ";" operator executes all commands regardless of whether the previous ones failed or not.

  10. shell

    As WP says, $(()) can only contain arithmetic expressions and therefore, a general ternary assignment doesn't exist in Bash. - zakmck. Commented Apr 10, 2023 at 18:49. @zakmck i think you should check again. try the code in the example. - mikeserv. Commented Sep 24, 2023 at 2:07.

  11. Arrays (Bash Reference Manual)

    The '+=' operator will append to an array variable when assigning using the compound assignment syntax; see Shell Parameters above. ... and bash will create an array if necessary. An array variable is considered set if a subscript has been assigned a value. The null string is a valid value. It is possible to obtain the keys (indices) ...

  12. Shell Arithmetic (Bash Reference Manual)

    Next: Aliases, Previous: Bash Conditional Expressions, Up: Bash Features 6.5 Shell Arithmetic The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin.

  13. Bash Shell Scripting/Shell Arithmetic

    The notation for this is similar to that of regular variable assignment, but is much more flexible. For example, the previous example could be rewritten like this: ... Bash also supports compound operators such as +=, -=, *=, /=, and %=, which perform an operation followed by an assignment.

  14. Bash Reference Manual

    1.1 What is Bash? Bash is the shell, or command language interpreter, for the GNU operating system. The name is an acronym for the 'Bourne-Again SHell', a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell sh, which appeared in the Seventh Edition Bell Labs Research version of Unix. Bash is largely compatible with sh and incorporates useful features from the ...

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

  16. Conditional Constructs (Bash Reference Manual)

    3.2.5.2 Conditional Constructs. The syntax of the if command is: consequent-commands; more-consequents;] The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding ...

  17. testing

    In BASH and other Bourne type shells, the if command merely runs the command, and if the command returns an exit code of 0, it executes the commands in the if clause. If the command does not return an exit code of 0, it skips the commands in the if clause and executes the commands in the else clause if it exists.. Thus, this is also valid: if sleep 2 then echo "That was a good nap!"

  18. Bash arrays: compound assignments fail

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