The && and || operators are used in shell scripting to control the flow of command execution based on the success or failure of previous commands.
&& Operator
- Function: Executes the next command only if the previous command succeeded (returned a zero exit status).
- Usage: Useful for chaining commands where each command depends on the success of the previous one.
Example:
mkdir new_directory && cd new_directory
In this example, cd new_directory will only execute if mkdir new_directory is successful.
|| Operator
- Function: Executes the next command only if the previous command failed (returned a non-zero exit status).
- Usage: Useful for providing alternative actions when a command fails.
Example:
rm file.txt || echo "File not found"
Here, echo "File not found" will execute only if rm file.txt fails (e.g., if the file does not exist).
Combining && and ||
You can combine both operators to create complex command chains that handle success and failure scenarios effectively.
Example:
command1 && command2 || command3
- If
command1succeeds,command2runs. - If
command1fails,command3runs.
This allows for flexible command execution based on the outcomes of previous commands. If you have more questions or need examples, feel free to ask!
