- Introduction
System Information
- Inter-Process Communication
- Signals
Programming in Various Environments
- Script Programming
- Script Variables
- Test Conditions
- Control and Iteration
- Commonly used Programs
- Shell Capabilities
- Example looping script
- Example using Variables
- Example working with files
- Example install script
- C and C++ Programming
- POSIX System Capabilities
- More POSIX
- Threads
- Mutexes
- An example viewmod program
- An example serial program
- X Programming
- Debugging
- Credits
|
Control and Iteration
- if - Used to execute one or more statements on a condition. An example:
if [ ! -d /mnt ] # be sure the directory /mnt exists
then
mkdir /mnt
fi
- case - Used to execute specific commands based on the value of a variable. An example:
case $NUM
1)
echo The number is 1
;;
2)
echo The number is 2
;;
*)
echo The number is not 1 or 2
;;
esac
- for - Used to loop for all cases of a condition. In the example below, it is used to copy all files found in /mnt/floppy to the /etc directory. The lines were numbered for reference with descriptions:
- The for loop statement will loop until all files have been found.
- A test to be sure the file is a normal file and not a directory.
- A comment line.
- This line extracts the name of the file from its full path pointed to by the variable $i and puts it in the variable $filename. The method used here is called parameter expansion and is documented in the bash man page. For more information on parameter expansion read the "Linux Programmer's Guide".
- This line sends a statement to the standard output, telling what file is being copied.
- This line performs the copy command using the -p option to preserve file attributes. Note: Much ability to perform script programming is couched in the ability to know and use the various commands, programs and tools available in Linux rather than a strict understanding of syntax. This is obvious to anyone who reads the system startup script files in /etc/rc.d and associated directories.
- This line ends the if statement.
- This line ends the for statement.
1. for i in /mnt/floppy/*; do
2. if [ -f $i ]; then
3. # if the file is there
4. filename=${i#/mnt/floppy/}
5. echo copying $i to /etc/$filename
6. cp -p $i /etc/$filename
7. fi
8. done
- until - Cycles through a loop until some condition is met. The syntax for the command is shown below:
until [ expression ]
do
statements
done
- while - Cycles through a loop while some condition is met. The below example will cycle through a loop forever:
while [ 1 ]
do
statement(s)
done
|
|
|
|