Why Shell Scripts?
Shell scripts automate repetitive tasks, streamline development workflows, and glue tools together. Every developer should know basic shell scripting.
bash
# Instead of running 10 commands manually
git pull origin main
npm install
npm run build
npm test
# ...
# Create script
./scripts/deploy.sh
# One command!Basics
Shebang and Variables
bash
#!/bin/bash
# Variables
NAME="World"
echo "Hello $NAME!"
# Arguments
echo "First arg: $1"
echo "All args: $@"
# Environment variables
export NODE_ENV=productionConditionals
bash
if [ "$NODE_ENV" = "production" ]; then
echo "Production mode"
elif [ "$NODE_ENV" = "development" ]; then
echo "Development mode"
else
echo "Unknown mode"
fiLoops
bash
# For loop
for file in *.js; do
echo "Processing $file"
done
# While loop
while read line; do
echo "$line"
done < input.txtFunctions
bash
deploy() {
local env=$1
echo "Deploying to $env"
# deployment logic
}
# Call function
deploy productionError Handling
bash
set -e # Exit on error
set -u # Exit on undefined variable
set -o pipefail # Exit on pipe error
trap 'echo "Error on line $LINENO"' ERRCommon Patterns
Project Setup Script
bash
#!/bin/bash
# scripts/setup.sh
echo "Setting up project..."
# Install dependencies
npm install
# Copy env file
cp .env.example .env
# Setup database
npm run db:migrate
echo "Setup complete!"Deployment Script
bash
#!/bin/bash
# scripts/deploy.sh
ENV=${1:-staging}
echo "Deploying to $ENV"
# Run tests
npm test
# Build
npm run build
# Deploy
if [ "$ENV" = "production" ]; then
npm run deploy:prod
else
npm run deploy:staging
fiBest Practices
- 1Use
set -efor error handling - 2Quote variables:
"$VAR" - 3Use local variables in functions
- 4Add comments for complex logic
- 5Make scripts executable:
chmod +x script.sh
Conclusion
Shell scripting is essential for automation. Start with simple scripts and gradually build more complex automation.
Automate everything!