Introduction to Bash Scripting
Alex Scriven
Data Scientist
Python:
for x in range(3):
print(x)
0
1
2
R:
for (x in seq(3)){
print(x)
}
[1] 1
[1] 2
[1] 3
The basic structure in Bash is a similar:
for x in 1 2 3
do echo $x done
1
2
3
Bash has a neat way to create a numeric range called 'brace expansion':
{START..STOP..INCREMENT}
for x in {1..5..2}
do echo $x done
1
3
5
Another common way to write FOR loops is the 'three expression' syntax.
x=2
)x<=4
)x+=2
)
for ((x=2;x<=4;x+=2))
do
echo $x
done
2
4
Bash also allows pattern-matching expansions into a for loop using the *
symbol such as files in a directory.
For example, assume there are two text documents in the folder /books
:
for book in books/*
do
echo $book
done
books/book1.txt
books/book2.txt
Remember creating a shell-within-a-shell using $()
notation?
You can call in-place for a for loop!
Let's assume a folder structure like so:
We could loop through the result of a call to shell-within-a-shell:
for book in $(ls books/ | grep -i 'air')
do echo $book done
AirportBook.txt
FairMarketBook.txt
Similar to a FOR loop. Except you set a condition which is tested at each iteration.
Iterations continue until this is no longer met!
while
instead of for
-le
)&&
(AND) or ||
(OR)Here is a simple example:
x=1
while [ $x -le 3 ];
do echo $x ((x+=1)) done
1
2
3
Beware the infinite WHILE loop, if the break condition is never met.
x=1
while [ $x -le 3 ];
do
echo $x
# don't increment x. It never reaches 3!
# ((x+=1))
done
This will print out 1 forever!
Introduction to Bash Scripting