Basic Linux Shell Scripting Concepts


By Corey Hynes, September 5th, 2002 Posted in Linux. Subscribe to our RSS Feed



Rather Have Fast and Secure Remote Control?

 Securely access PCs and servers worldwide through any firewall. Try it and see for yourself!

Variables

Shell scripts become more useful through the use of variables. Variables store information to be used at a later time. To define a variable, simply assign it a value as follows.

[myVar=”Hello World”]

Then to retrieve the value, prefix the variable with a $. Note that all variables are case sensitive.

[Echo $myVar]

Variables can be numeric as well. This are treated no differently than string variables.

Num1=3

Num2=3

Result = $Num1+$Num2

Echo The answer is $Result

Note that variables do not have to be defined in the shell script to be used. Environment variables can also be referenced as well. This allows you to create scripts that reference home directories, application directories and environment settings.

Conditional Logic

Conditional execution of programs is accomplished via IF statements. In the bash shell, the syntax is as follows.

if test; then
code
elif test; then
code
else
code
fi

The test is a logical operation that evaluates to true or false. If the evaluation is true then the code in the statement executes. Here are some examples of expressions.

Expression, Purpose

[ -f “somefile” ]: Test if somefile is a file.

[ -x “/bin/ls” ]: Test if /bin/ls exists and is executable.

[ -n “$var” ]: Test if the variable $var contains something

[ “$a” = “$b” ]: Test if the variables “$a” and “$b” are equal

Here is an example of a script that uses the environment variable to check what the users shell is.

#!/bin/sh
if [ "$SHELL" = "/bin/bash" ]; then
echo "You are using BASH)"
else
echo "You are not using BASH, you are using $SHELL"
fi

Written by Corey Hynes - Visit Website

Go To Page: 1 2 3 4 5



Print This Post Print This Post













All Tutorials by Category:















Entire site Copyright © 1999-2007 2000Trainers.com, all rights reserved.
Content on this site may not be copied or reproduced in any way without permission.





IT Showcase


Text Link Ads

View all Tutorials by Category: