Wednesday 11 May 2011

Conditional scripting

When you break programming down, regardless what language or syntax it is written or developed in, the basis of a piece of code is how it handles a condition.

What happens when you have something? How do you handle it? What do you do with it?

The absolute basic conditional statement in shell scripting is the "if" statement. The basics of the if is that "if the conditions are met, then do something". To be fancier, you can also add "else". Here is an example:

#!/usr/bin/sh

variable1=Hello;
variable2=Goodbye;

echo "Let's start!";
if [ "$variable1" = "$variable2" ]; then
  echo "The salutations are the same!";
else
  echo "The salutations are not the same!";
fi

variable2=Hello;
echo "";
echo "Let's try again!";
if [ "$variable1" = "$variable2" ]; then
  echo "The salutations are the same!";
else
  echo "The salutations are not the same!";
fi

This simple script sets up 2 variables, and the compares them. In the second paragraph, it changes the second variable to be the same as the first variable, and runs the same if statement test on them again. The output looks like:

$ ./test.sh
Let's start!
The salutations are not the same!

Let's try again!
The salutations are the same!

While not very exciting, you can do many different types of data. Keep in mind that comparing text is different from comparing data. More comparison tests can be found here.

Lastly, I would like to mention that you can put a shell script into a type of "debug" mode where it will output more verbose information while it is running. This is by changing the first line of the script from:

#!/usr/bin/sh

to

#!/usr/bin/sh -x

Now the output looks like:

$ ./test.sh
variable1=Hello
variable2=Goodbye
+ echo Let's start!
Let's start!
+ [ Hello = Goodbye ]
+ echo The salutations are not the same!
The salutations are not the same!
variable2=Hello
+ echo

+ echo Let's try again!
Let's try again!
+ [ Hello = Hello ]
+ echo The salutations are the same!
The salutations are the same!

Good luck with your scripting, and I welcome any comments or queries.

No comments:

Post a Comment