Skip to main content

Basic Bash Scripting

3.1 Your First Script​

Required location: ~/linux_tutorial/scripts

Navigate to the scripts directory:

cd ~/linux_tutorial/scripts
pwd # Should show your path ending with /linux_tutorial/scripts

Create your first script:

nano hello_world.sh

Add the following content:

#!/bin/bash
# This is a simple bash script
# The first line (shebang) tells the system which interpreter to use

echo "Hello, World!"
echo "Welcome to Linux scripting!"

Save and exit (Ctrl+X, then Y, then Enter in nano).

3.2 Making Scripts Executable​

Check current permissions:

ls -l hello_world.sh

Make the script executable:

chmod +x hello_world.sh

Check permissions again:

ls -l hello_world.sh

Notice the 'x' permission is now added.

Run your script:

./hello_world.sh

3.3 Script with Variables and Date​

Current location: ~/linux_tutorial/scripts

Make sure you're still in the scripts directory:

pwd # Should show your path ending with /linux_tutorial/scripts

Create a second script:

nano system_info.sh

Add this content:

#!/bin/bash
# System Information Script
# This script displays basic system information

# Get current date and time
current_date=$(date)

# Get current user
current_user=$(whoami)

# Display information
echo "=== System Information ==="
echo "Current Date: $current_date"
echo "Current User: $current_user"
echo "Current Directory: $(pwd)"
echo "========================="

Make it executable and run:

chmod +x system_info.sh
./system_info.sh

3.4 Interactive Script with User Input​

Current location: ~/linux_tutorial/scripts

Verify you're in the scripts directory:

pwd # Should show your path ending with /linux_tutorial/scripts

Create a personalized script:

nano personal_greeting.sh

Add this content:

#!/bin/bash
# Personal Greeting Script
# This script asks for user information and provides a customized greeting

# Prompt user for their name
echo "Please enter your name:"
read user_name

# Prompt user for their age
echo "Please enter your age:"
read user_age

# Calculate birth year (approximate)
current_year=$(date +%Y)
birth_year=$((current_year - user_age))

# Display personalized message
echo ""
echo "=== Personal Greeting ==="
echo "Hello, $user_name!"
echo "You are $user_age years old."
echo "You were born around $birth_year."
echo "Welcome to the world of Linux scripting!"
echo "========================"

Make it executable and test:

chmod +x personal_greeting.sh
./personal_greeting.sh