Automate, optimize, and streamline your workflows with professional scripting techniques
The shebang line specifies the interpreter. Always declare variables with meaningful names and use quotes to prevent word splitting.
#!/bin/bash
NAME='Linux Expert'
echo 'Hello $NAME'
💡 Use readonly for constants
Modern bash supports double brackets for pattern matching and regex comparisons. Always quote variables in conditionals.
if [[ -f 'file.txt' ]]; then
echo 'File exists'
fi
💡 Use [[ ]] for advanced tests
Parameter expansion provides powerful string manipulation capabilities directly in bash.
echo ${VAR:-default}
${VAR%%.*} # Remove extension
💡 Use ${VAR?} for required params
Treat command output as temporary files for complex pipelines.
diff <(ls dir1) <(ls dir2)
💡 Use >(cmd) for output
Ensure proper cleanup and graceful shutdown of long-running scripts.
trap 'cleanup' EXIT SIGINT SIGTERM
💡 Reset traps with trap - SIGNAL
Bash 4+ supports complex data structures for advanced scripting.
declare -a files=()
declare -A config=([user]=admin)
💡 Use += for appending
AWK is ideal for column-based data processing and reporting.
awk '/error/ {count++} END {print count}' log.txt
💡 Use BEGIN for initialization
Combine grep options like -ivrn for powerful text searching.
grep -P '\d{3}-\d{4}' contacts.txt
💡 Use -E for extended regex
Embed documents/templates directly in scripts.
cat <<EOF
Multi-line
content
EOF
💡 Use <<- to strip tabs
Create user-friendly command-line interfaces with validation.
import argparse
parser = argparse.ArgumentParser()
💡 Use click for complex CLIs
Context managers ensure proper resource cleanup.
with open('file.txt') as f:
data = f.read()
💡 Use pathlib for paths
Safely execute system commands with proper error handling.
subprocess.run(['ls', '-l'], check=True, capture_output=True)
💡 Use shlex.split for complex commands
Maintain manageable log files and prevent disk space issues.
/var/log/*.log {
daily
rotate 7
compress
delaycompress
}
💡 Test with logrotate -d
Create robust managed services with automatic restarts.
[Service]
ExecStart=/path/to/script.sh
Restart=on-failure
💡 Use journalctl for logs
Prevent hung processes from affecting system operations.
timeout 30s long_running.sh
💡 Use --preserve-status
Always sanitize and validate external inputs
if [[ ! -f "$INPUT_FILE" ]]; then
echo "Invalid file" >&2
exit 1
fi
Implement comprehensive error recovery
set -eo pipefail
trap 'error_handler $LINENO' ERR
Maintain inline and external documentation
## Purpose: Automated backup script
## Usage: ./backup.sh [OPTIONS]
Manage scripts with Git
git init
git add .
git commit -m 'Initial script version'
Trace script execution
bash -x script.sh
Enable debug mode in script
set -x
# Your code
set +x
Trace individual commands
trap 'echo "Executing: $BASH_COMMAND"' DEBUG
Custom debug prompt
PS4='+ ${BASH_SOURCE}:${LINENO}: '
Static analysis tool
shellcheck script.sh
Python debugger
python3 -m pdb script.py