Open Source Software and Linux

Jan 24 2009   8:01PM GMT

Setting script variables using the if..then statement

John Little Profile: Xjlittle

Recently I found myself wanting to set some variables in a script that I was writing using the if..then statement. I am using the Korn shell but this is bash compatible.

I wanted to do this as the variable command changed depending on if the script was running on Linux, HP-UX or AIX. This saved a ton of typing the same test over and over throughout the script which is about 600 lines.

The basic form of the script is

if [[ $STRING != string ]]; then
VARIABLE=string1
else
VARIABLE=string2
fi

As you can see the if statement is built around the VARIABLE rather than VARIABLE=if statement. Doing it in that form either won’t return any output or give you output that is not useful.

A real world example

VENDOR=$(uname)
if [ $VENDOR != "Linux" ];then
BACKUPHEADER=log "$(date '+%D %T') Checking header."
else
BACKUPHEADER=/bin/logger -t "VALIDATE LINUX BACKUP: $(date '+%D %T') Checking header."
fi

As you can see from the above the Unix command for sending output to syslog is log and is logger on Linux. Now imagine having to run various tests throughout the script and sending the output to syslog depending on the OS. As I mentioned, it saved quite a bit of typing.

Hope this helps you somewhere!

-j

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: