Páginas

Tuesday, September 14, 2010

Bash 101: The Shell as a Programming Language

There are two different ways of writing shell programs, interactively (type a sequence of commands on the shell and let it execute them), or store the commands in a file that can be invoked as a program. We'll focus on the later, but having in mind that they are pretty much alike.

The first little "trick" you should be aware of are the wildcard expansions (or globbing), here are some of the most used:
  • * - Matches any string of characters
  • ? - Matches any character
  • [...] - Matches the defined characters
  • [^...] - Negates the previous one (everything but what matches)
  • {...} -  Matches the specified strings
Here's an example of the last one:
ls my_{file,doc}s

Which will list the files my_files and my_docs.

There is another thing you should know before starting to write bash scripts and that's the $(...) operation. What it does is represent the output of the program you invoke inside the brackets. Let's see it with an example:

Note:
  1. If the string contains spaces it must be delimited by quote marks;
  2. There can't be any spaces before or after the equal sign.
You can also assign user input to a variable, using read. It waits for the user to write something and press Enter. At that moment the variable has been assigned what the user wrote:

$read variable
abcde (Enter)
$echo $variable
abcde


At this time you're ready for your first program. In order to do that just open your favorite text editor and write the commands.

Comments in bash are represented by the character #, and continue to the end of the line. The only exception is the first line that should start with #! and the path to the program used to run the file (usually /bin/bash). Also by convention the last line of the file should be exit 0 (for now just know that 0 represents successful in shell programming).

The actual script could be something like this:

#!/bin/bash

echo "Name of file to cat:"
read file
cat $file

greeting="\nHello World"
echo -e $greeting

exit 0


This script waits for the name of a file, "cats" it and then writes Hello World to the output (not worrying with errors such as the file not existing).

The final step is to make the file executable, with chmod:
$chmod +x file
and run it!
$./filename

No comments: