-
Notifications
You must be signed in to change notification settings - Fork 1
Tutorial 07
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.)
A bash file is any text file with the .sh extension.
To make a script executable:
$ chmod +x filename.shTo run it:
$ ./filename.shYou can repeat a task using a for loop. Here's a simple example:
for i in {1..10}
do echo $i
doneThis 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
doneYou can also run a loop directly in one line:
$ for i in {1..10}; do echo $i; done .sh files — they’re easier to read, reuse, and save.
Bash supports basic logic through if statements.
if [ "foo" = "foo" ]
then
echo "expressions are the same"
fiWith an else:
if [ "foo1" = "foo2" ]
then
echo "expressions are the same"
else
echo "expressions are not the same"
fiYou 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"
fiAlternative syntax with double parentheses (for numeric comparisons):
((2 >= -2))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
doneUse # 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
doneEach new line needs its own # if you want to keep commenting.
You’ve learned how to automate tasks, use loops, write conditions, and comment your scripts effectively. 🧠💻
➡️ Time to move on to Tutorial 8!