Here's an example of how to write a shell script.
edit a file in your home directory called
my_test_script.sh put this content in it:
Code:
#!/bin/bash
echo "Here is an example of a shell script"
echo "1a. File listing"
ls
echo ""
echo "1b. File listing with details (long format, just the first few lines)"
ls -l |head -n 5
echo ""
echo "2. Printing a calendar for the current month"
cal
echo ""
echo "3. Here's a little for loop"
n=1
for f in The quick brown fox jumps over the lazy dog; do
echo " Word number $n is $f"
let n+=1
done
echo ""
echo "Right, I'm all done. Bye bye."
Now, in a terminal, use this command to make the script executable:
Code:
chmod a+x my_test_script.sh
You could also make the script executable using a file manager like konqueror in KDE or Nautilus in gnome, but since you will execute the script from the terminal you might as well use chmod.
OK, to execute the script you need to use it's name. There is this thing called the PATH. This is a list of directory names which are searched for commands when a command is typed into the terminal. Usually your HOME directory is not in the PATH, and so we need to explicitly specify the path to the script. We can do this either by using the full path, or by using . to represent the current working directory.
Since I asked you to create the file in your home directory, you can refer to the file in either of these two ways:
Code:
$HOME/my_test_script.sh
~/my_test_script.sh
HOME is a variable which will be set to your home directory. We take the value of the variable using the $ prefix.
~ is a quick way to refer to your home directory.
Assuming the terminal session's present working directory (pwd) is your home directory, you can say "the file in the pwd, like this:
Code:
./my_test_script.sh
Enter any of these three and your script should run.
Note that the .sh extension is not compulsory. It is often used because it is useful to know what is in a file from looking at it's name, but the OS doesn't give a hoot about it.
Most commands which you will use in scripts are document in manual pages. You can read a manual page with the
man command in the terminal. For example to read the manual page for the
ls command, do this:
If you want to know how to use a command or what it can do, please check the manual page as youor first port of call.
If that has interested you, I'd recommend having a read of this:
http://tldp.org/LDP/abs/html/