In the previous two posts, I covered the basics of shell scripting. Here are the links:
1. Scripting in Linux
2. Scripting in Linux – Part 2
Today, we’ll use that knowledge to write a few scripts, understand their operation, and, most importantly, get you started with writing scripts on your own.
Script 1: Downloading files from a server
In this example, we’ll write a script that reduces your work when you have to download multiple files from a server. There are some prerequisites though:
- You must have a direct download link to the file.
- There must be some kind of a sequence in the remaining download links.
These conditions are usually satisfied. As an example, the other day I had to download a manga. The images hosted on the website’s server were something like:
http://c.mfcdn.net/store/manga/106/65-668.0/compressed/u001.jpg
The number coloured in red changed for every page and for every page it corresponded to the page number. Now for the script:
#!/bin/bash
echo "At what page number do you wish to begin?"
read firstpage
echo ""
echo "At what page number do you wish to finish? "
read lastpage
cd ~/Desktop/manga/
for(( i=firstpage; i<=lastpage; i++))
do
if [ "$i" -lt 10 ]
then
url="http://c.mfcdn.net/store/manga/106/65-668.0/compressed/u00"$a".jpg"
else
url="http://c.mfcdn.net/store/manga/106/65-668.0/compressed/u0"$a".jpg"
fi
wget -U Mozilla $url
done
echo ""
echo "Complete!"
Explanation:
The first couple of lines just get the starting and beginning page numbers. In the line number 9, we change our current directory to the folder in which we want to keep our files. Then follows a loop. The loop itself just loops over numbers starting from firstpage and ending at lastpage.
The condition inside the loop is for a different reason. If you look at the url closely, you’ll see that if the page number is less than 10, we have to put the page number by adding a zero in front of the page number. The condition checks whether the page number is less than 10, and, if it is, then, a url with the ‘extra’ zero is saved into the variable called url. In case the number is greater than 10, then there is no need for that extra zero.
Then, in line 19, we have used the inbuilt wget command. The options -U Mozilla ‘disguises’ the wget utility as Mozilla Firefox to the website’s server. And voila! You’re done.
I’ll keep adding more scripts here whenever I come across something useful. So, you can come back and check this page periodically. Also, please share this post on facebook if possible.