| name | bash |
| description | Bash shell scripting for automation, system administration, and command-line productivity |
| license | MIT |
| compatibility | opencode |
| metadata | {"audience":"developers","category":"scripting"} |
What I do
- Write bash scripts for automation
- Process text with awk and sed
- Use find and xargs effectively
- Handle command-line arguments
- Manage environment variables
- Implement error handling
- Create utility functions
When to use me
When automating tasks, building CLI tools, or managing systems.
Basics
#!/bin/bash
name="World"
echo "Hello, $name!"
current_date=$(date +%Y-%m-%d)
files=$(ls)
colors=("red" "green" "blue")
echo "${colors[0]}"
echo "${colors[@]}"
declare -A config
config[host]="localhost"
config[port]="8080"
echo "${config[host]}"
Conditionals
if [ "$name" == "admin" ]; then
echo "Welcome admin"
elif [ "$age" -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
if [ -f "$file" ]; then
echo "Regular file"
fi
if [ -d "$dir" ]; then
echo "Directory"
fi
if [ -z "$var" ]; then
echo "Empty"
fi
if [[ "$str" == *"pattern"* ]]; then
echo "Contains pattern"
fi
Loops
for i in {1..5}; do
echo "Number: $i"
done
for file in *.txt; do
echo "Processing $file"
done
while read line; do
echo "$line"
done < file.txt
for color in "${colors[@]}"; do
echo "$color"
done
Functions
function greet() {
local name="$1"
echo "Hello, $name!"
}
greet "World"
function get_sum() {
local a=$1
local b=$2
echo $((a + b))
}
result=$(get_sum 5 10)
Arguments
#!/bin/bash
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
help=true
;;
-n|--name)
name="$2"
shift 2
;;
-v|--verbose)
verbose=true
shift
;;
*)
echo "Unknown: $1"
shift
;;
esac
done
Error Handling
set -e
set -u
set -o pipefail
trap 'echo "Error on line $LINENO"' ERR
if ! command -v git &> /dev/null; then
echo "Git not found"
exit 1
fi
Text Processing
awk -F',' '{print $1, $3}' file.csv
awk 'NR>1 {sum+=$2} END {print sum}' file.txt
sed 's/old/new/g' file.txt
sed -i 's/old/new/g' file.txt
sed '/pattern/d' file.txt
find . -name "*.txt" -type f
find . -mtime -7
find . -size +1M
find . -name "*.log" -type f | xargs rm
find . -name "*.txt" | xargs -I {} mv {} ./backup/
Useful Patterns
command -v docker >/dev/null 2>&1 || { echo "Docker required"; exit 1; }
cat << EOF > config.txt
name=$name
value=$value
EOF
cat hosts | xargs -P 10 -I {} ssh {} 'uptime'
for i in {1..100}; do
echo -ne "Progress: $i%\r"
sleep 0.1
done