Chapter 7: Shell Scripting Basics in WSL Ubuntu (Automate with Bash)
Once you’re comfortable using Linux commands, it’s time to automate them. That’s where shell scripting comes in. In WSL Ubuntu, you can write Bash scripts to execute multiple commands automatically.
Shell scripts are used for everything from simple file backups to automated server setups. This chapter will show you how to write your first shell scripts step by step.
📜 What Is a Shell Script?
A shell script is a plain text file containing a series of Linux commands. Instead of typing each command manually, you save them in a file and run them all at once.
🧾 Create Your First Shell Script
📌 Step 1: Create a New File
nano hello.sh
📌 Step 2: Add This Code
#!/bin/bash
echo "Hello, $USER!"
echo "Today is $(date)"
echo "Your current directory is: $(pwd)"
📌 Step 3: Save and Exit
In nano, press:
Ctrl + O → Enter → Ctrl + X
📌 Step 4: Make It Executable
chmod +x hello.sh
📌 Step 5: Run the Script
./hello.sh
🎉 You’ve just run your first Bash script!
📌 Script Structure Explained
#!/bin/bash– Shebang line tells Linux to use Bashecho– Prints messages$(command)– Runs command and substitutes output$USER– Current user$(date)– Current date and time
📂 More Useful Commands in Scripts
ls -la
mkdir backup
cp *.txt backup/
df -h
You can include any Linux command in a shell script.
🧠 Using Variables
#!/bin/bash
name="Umar"
echo "Welcome, $name"
🔁 Adding Loops
#!/bin/bash
for file in *.txt
do
echo "Copying $file"
cp "$file" backup/
done
❓ Adding Conditions
#!/bin/bash
if [ -d "backup" ]; then
echo "Backup folder exists"
else
echo "Creating backup folder..."
mkdir backup
fi
🧪 Practice Challenge
Create a script named myscript.sh that:
- Greets the user
- Displays today’s date
- Creates a folder called
mybackupif it doesn’t exist - Copies all
.logfiles intomybackup
#!/bin/bash
echo "Hi $USER, welcome back!"
echo "Today is $(date)"
if [ ! -d "mybackup" ]; then
mkdir mybackup
fi
cp *.log mybackup/
✅ Summary
- Shell scripts are simple text files with Linux commands
- Use
#!/bin/bashat the top - Make scripts executable with
chmod +x - You can use variables, conditions, and loops
- Automate repetitive tasks with ease!
▶️ Coming Up Next
Chapter 8 – Networking Basics in WSL Ubuntu
Learn how to use commands like ping, ip, netstat, and check connectivity from WSL.
