Bash - run multiple commands in one line

In this article, we cover how to run multiple commands in one line in Bash. If there are multiple commands we have to run. Then, generally we run them in a sequence.

This is what most of us do, we run the command and wait for it complete the task. Once it results in an outcome, we then enter the second command. And, so on.

But, there is a better way to get this done unless we have to analyse the output of first command before issuing subsequent commands. All we have to do is – enter multiple commands separated either by semicolon(;) or two ampersand operators (&&).

With the help of either of these two i.e. semicolon and &&, we can issuing multiple commands in one go. Such commands we enter are processed in a sequence. Bash would let the first command finish before it goes ahead with the second command.

Use semicolon (;) to run multiple commands in one line

Use semicolon (;) to separate multiple commands –

command 1; command 2; command 3; ... command n

For instance, if following commands we intend to run in one line –

sudo apt update
sudo apt install gedit
cd /dev/shm
touch test.txt

Then, we can do –

sudo apt update; sudo apt install gedit; cd /dev/shm; touch test.txt

This would update the repository first, install gedit, get into /dev/shm directory and create an empty file – test.txt.

Use two ampersands (&&) to run multiple commands in one line

Alternately, we can use two ampersand operators (&&) in place of semicolon(;) to get the desired outcome –

command 1 && command 2 && command 3 && ... command n

Continuing with the above example –

sudo apt update && sudo apt install gedit && cd /dev/shm && touch test.txt

In conclusion, if there are multiple commands we have to run then it is better to enter them in one go. For that either use either semicolon(;) or two ampersand operators (&&). This saves us both time and effort. While the commands finish the task, we can utilize our time someplace else.

Similar Posts