In a Linux shell (like Bash), there are several ways to manage control flow to direct the execution of commands based on conditions or loops. These are the primary methods:
1. Conditional Statements
- if-else: Executes commands based on a condition.
if [ condition ]; then # commands else # commands fi
- elif: Used to check multiple conditions.
if [ condition ]; then # commands elif [ another_condition ]; then # commands else # commands fi
- case: Similar to
switch
in other languages, used for pattern matching.case $variable in pattern1) # commands ;; pattern2) # commands ;; *) # default case ;; esac
2. Loops
- for: Loops through a range or list of values.
for i in {1..5}; do # commands done
- while: Executes commands as long as a condition is true.
while [ condition ]; do # commands done
- until: Executes commands until a condition is true.
until [ condition ]; do # commands done
3. Exit Status and Control
- exit: Used to terminate the script with an optional exit status.
exit 0 # Success exit code exit 1 # Error exit code
- return: Used inside functions to exit with a status code.
return 1 # Exits function with a status
4. Logical Operators
- AND (
&&
): Executes the second command only if the first command succeeds.command1 && command2
- OR (
||
): Executes the second command only if the first command fails.command1 || command2
- Combination: Combine both
&&
and||
for complex conditions.command1 && command2 || command3
5. Loops with Break/Continue
- break: Exits the loop.
for i in {1..10}; do if [ $i -eq 5 ]; then break fi echo $i done
- continue: Skips the current iteration and proceeds to the next one.
for i in {1..5}; do if [ $i -eq 3 ]; then continue fi echo $i done
6. Command Grouping
- Semicolon (
;
): Executes multiple commands sequentially.command1; command2; command3
- Subshell (
( )
): Groups commands in a subshell.(command1; command2; command3)
- Background Execution (
&
): Runs the command in the background.command1 &
By combining these methods, you can create scripts that control the flow of execution in various ways.