http://www.freeos.com/guides/lsst/ch03sec02.html
http://www.freeos.com/guides/lsst/ch03sec03.html
http://codewiki.wikidot.com/shell-script:if-else
Shell scripts use fairly standard syntax for if statements. The conditional statement is executed using either the test command or the [ command. In its most basic form an if statement is:
(Notice that the fi is simply if spelled backwards). To add an else, we just use standard syntax.
Adding an else-if statement structure is used with the elif command.
An if statement does not require two parameters. You can use single
flags as well. The following code tests to see if the first parameter is
a file or not.
There are many different ways that an conditional statement can be used. These are summarized here:
#!/bin/bash
if [ "$1" -eq "cool" ]
then
echo "Cool Beans"
fi
#!/bin/bash
if [ "$1" -eq "cool" ]
then
echo "Cool Beans"
else
echo "Not Cool Beans"
fi
#!/bin/bash
if [ "$1" -eq "cool" ]
then
echo "Cool Beans"
elif [ "$1" -eq "neat" ]
echo "Neato cool"
else
echo "Not Cool Beans"
fi
#!/bin/bash
if [ -f "$1" ]
then
echo "$1 is a file"
else
echo "$1 is not a file"
fi
String Comparison | Description |
---|---|
Str1 = Str2 | Returns true if the strings are equal |
Str1 != Str2 | Returns true if the strings are not equal |
-n Str1 | Returns true if the string is not null |
-z Str1 | Returns true if the string is null |
Numeric Comparison | Description |
expr1 -eq expr2 | Returns true if the expressions are equal |
expr1 -ne expr2 | Returns true if the expressions are not equal |
expr1 -gt expr2 | Returns true if expr1 is greater than expr2 |
expr1 -ge expr2 | Returns true if expr1 is greater than or equal to expr2 |
expr1 -lt expr2 | Returns true if expr1 is less than expr2 |
expr1 -le expr2 | Returns true if expr1 is less than or equal to expr2 |
! expr1 | Negates the result of the expression |
File Comditionals | Description |
-d file | True if the file is a directory |
-e file | True if the file exists (note that this is not particularly portable, thus -f is generally used) |
-f file | True if the provided string is a file |
-g file | True if the group id is set on a file |
-r file | True if the file is readable |
-s file | True if the file has a non-zero size |
-u | True if the user id is set on a file |
-w | True if the file is writable |
-x | True if the file is an executable |
test command or [ expr ]
test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0), otherwise returns nonzero for false.Syntax:
test expression OR [ expression ]
Example:
Following script determine whether given argument number is positive.
$ cat > ispostive |
2
################
For Mathematics, use following operator in Shell Script
Mathematical Operator in Shell Script | Meaning | Normal Arithmetical/ Mathematical Statements | But in Shell | |
For test statement with if command | For [ expr ] statement with if command | |||
-eq | is equal to | 5 == 6 | if test 5 -eq 6 | if [ 5 -eq 6 ] |
-ne | is not equal to | 5 != 6 | if test 5 -ne 6 | if [ 5 -ne 6 ] |
-lt | is less than | 5 < 6 | if test 5 -lt 6 | if [ 5 -lt 6 ] |
-le | is less than or equal to | 5 <= 6 | if test 5 -le 6 | if [ 5 -le 6 ] |
-gt | is greater than | 5 > 6 | if test 5 -gt 6 | if [ 5 -gt 6 ] |
-ge | is greater than or equal to | 5 >= 6 | if test 5 -ge 6 | if [ 5 -ge 6 ] |
NOTE: == is equal, != is not equal.
For string Comparisons use
Operator | Meaning |
string1 = string2 | string1 is equal to string2 |
string1 != string2 | string1 is NOT equal to string2 |
string1 | string1 is NOT NULL or not defined |
-n string1 | string1 is NOT NULL and does exist |
-z string1 | string1 is NULL and does exist |
Shell also test for file and directory types
Test | Meaning |
-s file | Non empty file |
-f file | Is File exist or normal file and not a directory |
-d dir | Is Directory exist and not a file |
-w file | Is writeable file |
-r file | Is read-only file |
-x file | Is file is executable |
Logical Operators
Logical operators are used to combine two or more condition at a timeOperator | Meaning |
! expression | Logical NOT |
expression1 -a expression2 | Logical AND |
expression1 -o expression2 | Logical OR |
##########################3
Nested if-else-fi
You can write the entire if-else construct within either the body of the if statement of the body of an else statement. This is called the nesting of ifs.$ vi nestedif.sh |
http://www.freeos.com/guides/lsst/
http://www.dreamsyssoft.com/sp_ifelse.jsp
If/Else
In order for a script to be very useful, you will need to be able to test the conditions of variables. Most programming and scripting languages have some sort of if/else expression and so does the bourne shell. Unlike most other languages, spaces are very important when using an if statement. Let's do a simple script that will ask a user for a password before allowing him to continue. This is obviously not how you would implement such security in a real system, but it will make a good example of using if and else statements.
#!/bin/sh # This is some secure program that uses security. VALID_PASSWORD="secret" #this is our password. echo "Please enter the password:" read PASSWORD if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then echo "You have access!" else echo "ACCESS DENIED!" fiRemember that the spacing is very important in the if statement. Notice that the termination of the if statement is fi. You will need to use the fi statement to terminate an if whether or not use use an else as well. You can also replace the "==" with "!=" to test if the variables are NOT equal. There are other tokens that you can put in place of the "==" for other types of tests. The following table shows the different expressions allowed.
Comparisons:
-eq | equal to |
-ne | not equal to |
-lt | less than |
-le | less than or equal to |
-gt | greater than |
-ge | greater than or equal to |
File Operations:
-s | file exists and is not empty |
-f | file exists and is not a directory |
-d | directory exists |
-x | file is executable |
-w | file is writable |
-r | file is readable |
Let's try using a couple of these in a script. This next script will ask for a user name, if there is not a file that exists with the name "username_DAT", the script will prompt the user for their age, it will then make sure that they are old enough to use this program and then it will write their age to a file with the name "username_DAT". If the file already exists, it will just display the age of the user.
#!/bin/sh # Prompt for a user name... echo "Please enter your name:" read USERNAME # Check for the file. if [ -s ${USERNAME}_DAT ]; then # Read the age from the file. AGE=`cat ${USERNAME}_DAT` echo "You are $AGE years old!" else # Ask the user for his/her age echo "How old are you?" read AGE if [ "$AGE" -le 2 ]; then echo "You are too young!" else if [ "$AGE" -ge 100 ]; then echo "You are too old!" else # Write the age to a new file. echo $AGE > ${USERNAME}_DAT fi fi fiRun this program a couple of times. First run it and give it the user name of "john". When it asks for an age, enter the age "1". Notice that it will say that you are too you and then exit. Now run the program again with the name "john" and the age 200. This time the script will tell you that you are too old and exit. Now run the the script again with the name of "john", enter the age 30. The script exits normally this time, the program created a file called "john_DAT" which contains the text "30". Finally run the program one more time and give it the name "john". This time it will not prompt you to enter an age, instead it will read the age from a file and say "Your are 30 years old!".
We introduced something else new in this script. On line 10 of the file, we see the code:
AGE=`cat ${USERNAME}_DAT`This is how you execute a command and put the text output from the command into a variable. The unix command cat reads the file named ${USERNAME}_DAT and outputs it to the console. Instead of putting it to the console in our script, we wrap the command with the character `, this puts the text into our variable AGE.
You can test multiple expressions at once by using the || (or) operator or the && (and) operator. This can save you from writing extra code to nest if statements. The above code has a nested if statement where it checks if the age is greater than or equal to 100. This could be changed as well by using elif (else if). The structure of elif is the same as the structure of if, we will use it in an example below. In this example, we will check for certain age ranges. If you are less than 20 or greater than 50, you are out of the age range. If you are between 20 and 30 you are in your 20's and so on.
#!/bin/sh # Prompt for a user name... echo "Please enter your age:" read AGE if [ "$AGE" -lt 20 ] || [ "$AGE" -ge 50 ]; then echo "Sorry, you are out of the age range." elif [ "$AGE" -ge 20 ] && [ "$AGE" -lt 30 ]; then echo "You are in your 20s" elif [ "$AGE" -ge 30 ] && [ "$AGE" -lt 40 ]; then echo "You are in your 30s" elif [ "$AGE" -ge 40 ] && [ "$AGE" -lt 50 ]; then echo "You are in your 40s" fi
No comments:
Post a Comment