Advertisement
linuxserver Bash scripting is a powerful way to automate tasks on Linux or macOS. In this tutorial, you’ll write scripts that do real things immediately, without long theoretical explanations. By the end, you’ll have scripts to create files, manage directories, and automate backups

Practical Bash Scripting: Automate Tasks Quickly

5 Min Read Verified Content

Script 1: Hello World and Variables

#!/bin/bash # Print hello and use variables NAME="Alice" echo "Hello, $NAME! Welcome to Bash scripting." # You can also read input from user read -p "Enter your favorite color: " COLOR echo "Your favorite color is $COLOR."

Run it:

chmod +x script1.sh ./script1.sh

Immediate insight:

  • $NAME → variable usage

  • read -p → takes user input



Script 2: Looping Through Files

#!/bin/bash # List all .txt files in current directory for file in *.txt do echo "Found file: $file" done

Run it:

./script2.sh

Insight:

  • for file in *.txt → iterates over files matching the pattern

  • Useful for batch processing



Script 3: Conditional Logic

#!/bin/bash # Check if a directory exists DIR="backup" if [ -d "$DIR" ]; then echo "Directory $DIR exists." else echo "Directory $DIR does not exist. Creating it..." mkdir "$DIR" fi

Immediate insight:

  • [ -d "$DIR" ] → checks if a directory exists

  • mkdir → creates directory



Script 4: Simple Backup Script

#!/bin/bash # Backup .txt files to backup folder SRC_DIR="." DEST_DIR="backup" mkdir -p "$DEST_DIR" # create backup folder if not exists for file in *.txt do cp "$file" "$DEST_DIR/" echo "Backed up $file to $DEST_DIR/" done

Run it:

./script4.sh

Immediate insight:

  • mkdir -p → creates folder only if it doesn't exist

  • cp → copies files

  • This script can run daily with cron for automation



Script 5: Simple Logging

#!/bin/bash # Log current date and list of files LOG_FILE="script.log" echo "Run on $(date)" >> "$LOG_FILE" ls >> "$LOG_FILE" echo "Logged current directory files."

Immediate insight:

  • >> → append output to a file

  • Useful for recording actions or cron jobs


Summary

In this style:

  • You write working scripts first

  • See results immediately

  • Learn by running and modifying

Advertisement
Back to Linuxserver