Master One‑Liner Linux Commands: Using ; && || to Chain Tasks
Learn how to run multiple Linux commands on a single line using the semicolon, &&, and || operators, with clear syntax explanations, practical examples, and tips for controlling execution flow based on success or failure.
Why chain commands?
Running several commands in one line saves time and improves efficiency in Linux environments.
Three operators
;– executes commands sequentially regardless of success. && – executes the next command only if the previous one succeeds. || – executes the next command only if the previous one fails.
Using the semicolon
Example syntax: cmd1; cmd2; cmd3 In this sequence, cmd1 runs first; cmd2 runs after it finishes, regardless of success; then cmd3 runs.
Sample session:
[root@localhost ~]# mkdir /root/new_folder; cd /root/new_folder; touch test_file; pwd; ls -l
/root/new_folder
total 0
-rw-r--r--. 1 root root 0 Sep 2 22:01 test_fileThe commands create a directory, change into it, create an empty file, display the current path, and list the file details.
Using &&
The logical AND ensures the following command runs only when the preceding command exits with a zero status. yum makecache && yum -y update Here the package cache is refreshed first; only if that succeeds are all packages updated.
Using ||
The logical OR runs the next command only when the previous command fails. cmd1 || cmd2 || cmd3 If cmd1 fails, cmd2 runs; if cmd2 succeeds, cmd3 is skipped.
Combining && and ||
You can test conditions such as file existence in a single line:
[ -f file.txt ] && echo "File exists" || echo "File doesn't exist"When file.txt is present, the first echo runs; otherwise the second echo runs.
Summary
Using ;, &&, and || to chain commands on one line can dramatically speed up routine tasks and give fine‑grained control over execution flow in Linux.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
