Articles

Help understanding shell script

March 27, 2008 at 15:35:11
Specs: UNIX, 500

I have this script and I don't understand what this part of the script is doing. Any help is greatly appreciate.

if [ x"$1" = x"-tkdiff" ]; then
diffp=tkdiff
diffopt ="-b"
shift;
elif [ x"$1" = x"-ediff" ]; then
diffp=ediff
shift;
elif [ x"$1" = x"-emacs"]; then
diffp=xemacs
shift;
else
diffp=diff
diffopt=-b
fi

I particularly don't understand the x"$1" = x"-tkdiff" construct. What is x"$1" and what is the $1?

Thanks!



See More: Help understanding shell script

Report •


#1
March 27, 2008 at 19:12:38

First, generally, $1 is the first command argument of your script. (I say, generally, because the unix set comamnd can change $1, $2, etc. I'll ignore that for the purposes of this discussion). Assume your shell script is called x.ss. Executing:

x.ss -tkdiff

$1 will equal the string "-tkdiff". Executing x.ss with no command line arguments, sets $1 to null or undefined.

Consider this line:

if [ x"$1" = x"-tkdiff" ]; then

if $1 equals -tkdiff, the first part of the if statement executes; If $1 is undefined or equals some other value the else executes.

You're probably wondering why the guy did this? Why not just do this:


if [ "$1" = "-tkdiff" ]
then
echo "command line arg is -tkdiff"
fi

He should have. The "x" really doesn't get you anything. He probably modified a bourne shell null check.

While the korn and bash shells have a string null check (-z), the bourne shell does not. This is one way of checking with the bourne shell whether $1 is null:

#!/bin/sh


if [ x"$1" = x ]; then
echo "command line arg 1 is null"
else
echo "it exists"
fi

if $1 is null, then x equals x and the first part of the if statement identifies $1 as null.

Let me know if you have any questions.


Report •

#2
March 28, 2008 at 07:05:54

It makes sense! Your help is greatly appreciated.

Report •

Related Solutions


Ask Question