Shell Script Examples

Here's a fun trick. You can define (temporarily) a shell function using the command line. For several lines, when you press Enter, bash knows you are not finished, so it gives you a different prompt:

ubuntu@ubuntu:~/scripts$ function today { > echo "Today's date is:" > date +"%A, %-d %B %Y" > } ubuntu@ubuntu:~/scripts$ today

You should see the day of the week, then the day month and year.

Here docs

Now use gedit (or any other text editor that edits plain text) to make the following script, which we will call mkhtml:

ubuntu@ubuntu:~/scripts$ gedit mkhtml

The first line is called the shabang line for the first two characters. The # character is sometimes called a sharp (as in music) and the exclamation point is sometimes called a bang. This line tells the shell that this should be run by the program /bin/bash.

The # anywhere other than the first line means ignore everything to the end of the line — it is a comment.

The next line defines a variable named TITLE. By tradition, constants (within the program) or environmental variables are all in upper case. TITLE is defined to be the first argument (text separated by spaces) on the command line when it was run. $1 is the first argument, $2 the second, and so on. That means if you want to set the title to be more than one word, the title should be in quotes, like this:

ubuntu@ubuntu:~/scripts$ mkhtml "Title of My Page"

The constant RIGHT_NOW is set to be the result of the date command, formatted to show the day of the week, day month year, and time Zulu or Universal Time. The $( ) means do that in a subshell, and return whatever is produced.

The constant TIME_STAMP puts all that together.

The cat command means send what follows someplace. If you don't tell it where, it sends it to the screen. The << is a quoting operator called a "here doc" that means quote everything from the next argument until the exact same argument is on a line by itself. That means everything from EOF between underscores until it appears at the bottom is quoted text.

More common quoting operators are the single and double quotes. The difference between them is that double quotes allow normal substitution of things like variables, while single quotes allow only very limited substitution.

Try these examples:

ubuntu@ubuntu:~/scripts$ tapir=April ubuntu@ubuntu:~/scripts$ tiger=Jaguar ubuntu@ubuntu:~/scripts$ echo "My friend $tapir met a "$tiger"" ubuntu@ubuntu:~/scripts$ echo "My friend $tapir met a '$tiger'" ubuntu@ubuntu:~/scripts$ echo "My friend $tapir met a $tiger" ubuntu@ubuntu:~/scripts$ echo "My friend $tapir met a "$tiger"" ubuntu@ubuntu:~/scripts$ echo 'My friend $tapir met a $tiger' ubuntu@ubuntu:~/scripts$ echo 'My friend $tapir met a '$tiger''

This page is
made possible by:

This page rendered by CodeIgniter in 0.0546 seconds.