Bash Operators in Linux
Although Linux Distributions provide a Graphical User Interface just like any other operating system, the ability to control the system via the command line interface (CLI) has many benefits. A way to control how tasks are executed or how input and output is redirected, can be done using operators.
1) Command “chaining”
- Sequence: ;
Executing multiples tasks, one after another. After the first task is completed, the next task will execute. After the second is completed, the third will execute and so on:
- Parallel execution: &
2) Conditional execution:
- And operator: &&
- Or operator: ||
3) Pipelines: |, |&
- Pipe operator: |
- Pipe error operator: |&
Error output of Task1 (stderr) is also redirected to input of Task 2 (stdin)
4) Input / output redirection
- Redirecting input: <
Used for command that read their input from the terminal. Input is read from from file, instead of terminal
Syntax: command < file
- Redirecting input – here documents: <<
Used when the input of a command should be taken directly from the terminal, rather that from a file
- Redirecting input – here string: <<<
- Redirecting output – stdout: >, >>
Used for commands that write output to the terminal.
Syntax:
command > file – write output to file. If file doesn’t exist, it is created. If it exists, it will be truncated
command >> file – write output to file. If file doesn’t exists, it is created. If it exists, output will be appended
Note: Stderr is still written to the terminal
- Redirecting output – stderr: 2>, 2>>
Sends stderr to file.
Syntax:
command 2> file – write stderr to file. . If file doesn’t exist, it is created. If it exists, it will be truncated
command 2>> file – write stderr to file. If file doesn’t exist, it is created. If it exists, output will be appended
Note: Output (stdout) is still written to the terminal
- Redirecting output – stdout and stderr: &>, &>>
Used to redirect both stdout and stderr for the same command
Syntax:
command &> file – send stdout and stderr to file. If file doesn’t exist, it is created. If it exists, it will be truncated
command &>> file – send stdout and stderr to file. If file doesn’t exist, it is created. If it exists, output will be appended
Interested in finding out more about Linux? Check out our trainings.
Linux Expert