Running Multiple Linux Commands in One Line Using Shell Operators
This guide explains how to efficiently execute several Linux shell commands on a single line by using the semicolon, logical OR (||), and logical AND (&&) operators, including examples, combined operator usage, and how to automate tasks with shell scripts.
Linux terminals allow you to perform a wide range of system operations with shell commands, but running each command separately can be inefficient. By linking commands on a single line, you can speed up workflows and save time.
Linux provides three operators for chaining commands:
Semicolon ( ; )
Logical OR ( || )
Logical AND ( && )
All of these operators can run two or more commands together, but choosing the right one depends on the desired execution logic.
1. Using the Semicolon ( ; ) Operator
The semicolon runs each command in sequence regardless of the success or failure of the previous command. For example:
commandA ; commandBThis ensures that both commands execute even if the first one fails. A practical example is displaying the current user and hostname:
whoami ; hostname2. Using the OR ( || ) Operator
The OR operator runs the second command only if the first command fails. Example syntax:
commandA || commandBIf commandA succeeds, commandB is skipped. This is useful when you want to perform an alternative action only when a preceding command encounters an error, such as creating a file only if it does not already exist:
find . -name Document.txt || touch Document.txt3. Using the AND ( && ) Operator
The AND operator runs the next command only if the previous command succeeds. A common use case is creating a directory and immediately changing into it:
mkdir linuxmi && cd linuxmiCombining Multiple Operators
You can group operators to meet more complex conditions. For instance, to execute commandB and commandC only when commandA fails:
commandA || commandB && commandCAnother example checks for a directory, prints a message if it is missing, and creates it:
find . -name linuxmi1 || echo "Directory not found" && mkdir linuxmiRunning Multiple Commands with a Shell Script
Shell scripts let you automate a series of commands. Create a file with a .sh extension, make it executable with chmod +x script.sh , and run it using ./script.sh . This is especially handy for repetitive tasks like system updates:
#!/bin/bash
sudo apt update && sudo apt upgrade -yUsing these operators and scripts makes terminal work more efficient and helps both beginners and experienced users master the command line.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.