Combining multiple Linux commands is a common need to execute multiple tasks in a single line. Linux provides several methods to combine commands, with three primary approaches: using semicolon (;), logical AND (&&), and logical OR (||).
- Using semicolon (
;): This method allows multiple commands to be executed sequentially, regardless of the outcome of the previous command. For example:
bashls; pwd; whoami
This command lists the files and directories in the current directory, then prints the current working directory, and finally displays the current username.
- Using logical AND (
&&): With this method, the subsequent command executes only if the previous command succeeds (exit status 0). This is useful for executing multiple commands in sequence that depend on the success of the previous command. For example:
bashmkdir new_folder && cd new_folder && touch new_file.txt
Here, it switches to the directory and creates a new text file new_file.txt only if new_folder is successfully created.
- Using logical OR (
||): With this method, the subsequent command executes only if the previous command fails (exit status non-zero). This is commonly used in error handling scenarios. For example:
bashcd my_folder || echo "Folder not found."
This command attempts to change directory to my_folder; if the directory does not exist (i.e., the cd command fails), it outputs "Folder not found."
These combination techniques can be selected based on actual requirements and expected behavior, making command-line operations more flexible and powerful.