Linux 102: Shell Scripting Basics

Linux 102: Shell Scripting Basics


In the previous article, we explored the command line basics. Now it’s time to level up. Imagine running a set of Linux commands with a single file — that’s the power of shell scripting.

Shell scripts help you automate tasks, create tools, and even manage servers — all with plain text files and a little logic.


What Is a Shell Script?

A shell script is simply a text file containing a series of Linux commands executed in sequence by the shell (usually bash).


Creating Your First Script

Let’s create a basic script that prints “Hello, world!”

Step 1: Create a file

touch hello.sh

Step 2: Open and edit it

Use nano, vim, or your favorite editor:

nano hello.sh

Step 3: Add the following lines:

#!/bin/bash
echo "Hello, world!"
  • #!/bin/bash is the shebang — it tells the system to use bash to interpret this file.

Step 4: Make it executable

chmod +x hello.sh

Step 5: Run it

./hello.sh

Adding Variables

You can store and reuse data in scripts using variables:

#!/bin/bash
name="Kira"
echo "Welcome, $name!"

User Input

Let your script interact with users:

#!/bin/bash
echo "What's your name?"
read user_name
echo "Nice to meet you, $user_name!"

Conditions (If Statements)

#!/bin/bash
if [ -f "$1" ]; then
  echo "File $1 exists."
else
  echo "File $1 does not exist."
fi

Try running it like this:

./checkfile.sh myfile.txt

Loops

for Loop Example:

#!/bin/bash
for i in {1..5}
do
  echo "Count: $i"
done

while Loop Example:

#!/bin/bash
count=1
while [ $count -le 3 ]
do
  echo "Loop $count"
  ((count++))
done

Real-World Example: Backup Script

#!/bin/bash
backup_dir="$HOME/backup"
mkdir -p $backup_dir
cp *.txt $backup_dir
echo "Text files backed up to $backup_dir"

Wrapping Up

With shell scripting, you’ve unlocked automation. These are just the basics — in future articles, we’ll explore:

  • case statements
  • Functions
  • Scheduling with cron
  • Handling errors and logs

Next up: “Linux 103: Cron Jobs and Task Automation”

Post a Comment (0)
Previous Post Next Post

ads