Problem Statement
Explain different command chaining operators: semicolon (;), AND (&&), OR (||), and pipe (|). Provide examples of when to use each.
Explanation
Semicolon (;) executes commands sequentially regardless of success or failure: command1; command2; command3 runs all commands in order. Second command runs even if first fails. Use for independent commands where each should run regardless of previous results. Example: cd /tmp; ls lists /tmp even if cd failed (if already in /tmp).
AND operator (&&) executes next command only if previous succeeded (exit status 0): command1 && command2 runs command2 only if command1 succeeds. Use for dependent operations where second command should only run if first succeeds. Example: mkdir backup && cp file backup/ only copies if directory creation succeeds. Chain multiple: command1 && command2 && command3.
OR operator (||) executes next command only if previous failed (non-zero exit status): command1 || command2 runs command2 only if command1 fails. Use for fallbacks or error handling. Example: test -f file || touch file creates file only if doesn't exist. Common pattern: command || { echo "Error"; exit 1; } provides error handling.
Pipe (|) connects stdout of one command to stdin of next, creating data processing pipelines: command1 | command2 | command3. Data flows through commands. Use for filtering, transforming, or processing command output. Example: cat file | grep pattern | sort | uniq processes file through multiple filters.
Combining operators: cd /tmp && ls || echo "Failed" changes to /tmp, lists contents if cd succeeded, otherwise prints error. Parentheses create subshells for grouping: (command1 && command2) || command3 runs command3 if either in parentheses fails. Understanding chaining creates sophisticated command sequences handling success/failure appropriately.