Skip to content

Tutorial 07

Lee Burton edited this page Jul 13, 2025 · 2 revisions

🤖 Automating Tasks in the Shell

Bash allows you to automate tasks directly from the command line.
The easiest way to get started is to use vim to write bash scripts and then execute them.
(See Tutorial 3 for how to edit files with vim.)


📝 Bash Scripts

A bash file is any text file with the .sh extension.

To make a script executable:

$ chmod +x filename.sh

To run it:

$ ./filename.sh

🔁 for Loop

You can repeat a task using a for loop. Here's a simple example:

for i in {1..10}  
do echo $i  
done

This will print the numbers 1 to 10.

To change the step size (e.g., counting by 2):

for i in {1..10..2}  
do echo $i  
done

You can also run a loop directly in one line:

$ for i in {1..10}; do echo $i; done 

⚠️ But for anything complex, it's better to use .sh files — they’re easier to read, reuse, and save.


🤔 if Condition

Bash supports basic logic through if statements.

if [ "foo" = "foo" ]
then
echo "expressions are the same"
fi

With an else:

if [ "foo1" = "foo2" ]
then
echo "expressions are the same"
else
echo "expressions are not the same"
fi

🔎 Comparison Operators

You can compare strings or numbers using these operators:

Strings:

  • = : equal
  • != : not equal

Numbers:

  • -eq : equal to
  • -ne : not equal to
  • -gt : greater than
  • -ge : greater than or equal to
  • -lt : less than
  • -le : less than or equal to
if [ 2 -gt -2 ]
then
echo "2 is greater than -2"
fi

Alternative syntax with double parentheses (for numeric comparisons):

((2 >= -2))

🔁➕❓ For Loop + If Condition

You can combine for loops with if statements for powerful logic.

for i in {-5..5}
do 
  if [ $i -lt 0 ]
  then 
    echo "$i is a negative number" 
  else
    echo "$i is a positive number"
  fi 
done

💬 Commenting Code

Use # to leave comments in your script.
Good commenting is essential for clear, maintainable code.

for i in {-5..5}                # for a number between -5 and 5
do if [ $i -lt 0 ]              # if that number is less than 0
then 
echo "$i is a negative number"  # say that the number is negative
else
echo "$i is a positive number"  # otherwise say the number is positive
fi 
done

Each new line needs its own # if you want to keep commenting.


🎉 Congratulations!

You’ve learned how to automate tasks, use loops, write conditions, and comment your scripts effectively. 🧠💻

➡️ Time to move on to Tutorial 8!

Clone this wiki locally