Skip to content

Instantly share code, notes, and snippets.

@copyleftdev
Created August 24, 2024 06:49
Show Gist options
  • Save copyleftdev/b187f4fadf8d50d36753a00c93ca2cd0 to your computer and use it in GitHub Desktop.
Save copyleftdev/b187f4fadf8d50d36753a00c93ca2cd0 to your computer and use it in GitHub Desktop.
Bash Command Chaining Mastery: The Ultimate Cheat Sheet

πŸ”— Bash Command Chaining Mastery: The Ultimate Cheat Sheet

πŸ”— Basic Command Chaining

Operator Description Example
; πŸ“Š Run commands sequentially echo "Hello"; echo "World"
&& βœ… Run next command only if previous succeeds mkdir dir && cd dir
|| ❌ Run next command only if previous fails ping -c1 google.com || echo "Offline"
| 🚿 Pipe output of one command to another ls -l | grep ".txt"

πŸ”€ Command Grouping

Syntax Description Example
( ... ) 🐣 Run commands in a subshell (cd /tmp && ls) | grep log
{ ...; } πŸ“¦ Run commands in current shell { echo "Start"; ls; echo "End"; }

πŸ”„ Loop Constructs

Syntax Description Example
for πŸ” Iterate over a list for i in {1..5}; do echo $i; done
while πŸ”„ Run while condition is true while true; do date; sleep 1; done
until πŸ”„ Run until condition is true until ping -c1 google.com; do sleep 5; done

πŸ”€ Conditional Execution

Syntax Description Example
if...then...fi πŸ” Conditional execution if [ -f file.txt ]; then echo "Exists"; fi
case...esac πŸ”’ Multi-way decision case $var in 1) echo "One";; 2) echo "Two";; esac

πŸ”£ Input/Output Redirection

Operator Description Example
> πŸ“€ Redirect stdout to file (overwrite) echo "Hello" > file.txt
>> πŸ“₯ Redirect stdout to file (append) echo "World" >> file.txt
< πŸ“₯ Redirect file to stdin sort < unsorted.txt
2> 🚨 Redirect stderr to file gcc program.c 2> errors.log
&> πŸ“Š Redirect both stdout and stderr command &> output.log

πŸ”— Advanced Chaining Techniques

Technique Description Example
xargs πŸ”¨ Build command lines from standard input find . -name "*.txt" | xargs grep "pattern"
tee πŸ”± Send output to both file and stdout echo "log" | tee -a logfile.txt
command substitution πŸ”„ Use output of a command as argument echo "Today is $(date +%A)"
process substitution πŸ”„ Use output of command as file diff <(sort file1) <(sort file2)

πŸŽ›οΈ Job Control

Command Description Example
& πŸƒβ€β™‚οΈ Run command in background long_running_command &
jobs πŸ“‹ List background jobs jobs
fg ▢️ Bring job to foreground fg %1
bg πŸƒβ€β™‚οΈ Resume job in background bg %2
wait ⏳ Wait for background jobs to finish wait %1

πŸ† Pro Tips

  1. πŸ“š Use set -e at the start of your script to exit on any command failure
  2. πŸ” Use set -x for debugging to print each command before execution
  3. πŸ”’ Use $? to check the exit status of the last command
  4. πŸ”€ Combine && and \|\| for if-else like behavior: command && success_command \|\| failure_command
  5. πŸ” Use while read to process file contents line by line
  6. πŸ“₯ Use <<EOF for here-documents to pass multi-line input to a command
  7. πŸ”’ Use set -o noclobber to prevent accidental file overwrites with >
  8. πŸ”£ Remember that 2>&1 redirects stderr to stdout
  9. πŸ”¨ Use trap to set up commands that run on script exit or on signals
  10. πŸ“Š Use time command to measure execution time of commands or scripts

πŸ“œ Example: Combining Multiple Techniques

#!/bin/bash
set -e

# Function to process files
process_file() {
    echo "Processing $1"
    # Simulating processing with sleep
    sleep 1
}

# Find all .txt files and process them in parallel
find . -name "*.txt" | xargs -I {} -P 4 bash -c 'process_file "$@"' _ {}

# Wait for all background jobs to finish
wait

# Check if any errors occurred
if [ $? -eq 0 ]; then
    echo "All files processed successfully" | tee success.log
else
    echo "Some errors occurred during processing" | tee error.log >&2
fi

# Cleanup temporary files
rm -f *.tmp && echo "Cleanup completed" || echo "Cleanup failed"

Remember, with great power comes great responsibility. Use these techniques wisely to create efficient and readable Bash scripts! πŸš€πŸ’»

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment