Unix Shell Scripting For DBA’s (PART – 09)

 reference of this article from : www.orskl.com
CONDITIONS & INTERACTIVE SCRIPTS
  1. IF clause
  2. Advanced IF usage
  3. CASE statements
  4. Display user messages
  5. User input

1.IF clause

General

At times you need to specify different courses of action to be taken in a shell script, depending on the success or failure of a command. The if construction allows you to specify such conditions.

The most compact syntax of the if command is:

if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

The TEST-COMMAND often involves numerical or string comparison tests, but it can also be any command that returns a status of zero when it succeeds and some other status when it fails. Unary expressions are often used to examine the status of a file. If the FILE argument to one of the primaries is of the form /dev/fd/N, then file descriptor “N” is checked. stdin, stdout and stderr and their respective file descriptors may also be used for tests.

Expressions used with if

The table below contains an overview of the so-called “primaries” that make up the TEST-COMMAND command or list of commands. These primaries are put between square brackets to indicate the test of a conditional expression.

Primary expressions

Primary                      Meaning

[ -a FILE ]                     True if FILE exists.

[ -b FILE ]                     True if FILE exists and is a block-special file.

[ -c FILE ]                     True if FILE exists and is a character-special file.

[ -d FILE ]                     True if FILE exists and is a directory.

[ -e FILE ]                     True if FILE exists.

[ -f FILE ]                      True if FILE exists and is a regular file.

[ -g FILE ]                     True if FILE exists and its SGID bit is set.

[ -h FILE ]                     True if FILE exists and is a symbolic link.

[ -k FILE ]                     True if FILE exists and its sticky bit is set.

[ -p FILE ]                     True if FILE exists and is a named pipe (FIFO)

[ -r FILE ]                      True if FILE exists and is readable.

[ -s FILE ]                     True if FILE exists and has a size greater than zero.

[ -t FILE ]                      True if file descriptor FD is open and refers to a terminal.

[ -u FILE ]                     True if FILE exists and its SUID (set user ID) bit is set.

[ -w FILE ]                    True if FILE exists and is writable.

[ -x FILE ]                     True if FILE exists and is executable.

[ -O FILE ]                    True if FILE exists and is owned by the effective user ID.

[ -G FILE ]                    True if FILE exists and is owned by the effective group ID.

[ -L FILE ]                     True if FILE exists and is a symbolic link.

[ -N FILE ]                    True if FILE exists and has been modified since it was last read.

[ -S FILE ]                     True if FILE exists and is a socket.

[ FILE1 – nt FILE2 ]       True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.

[ FILE1 – ot FILE2 ]       True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not.

[ FILE1 – ef FILE2 ]       True if FILE1 and FILE2 refer to the same device and inode numbers.

[ -o OPTIONNAME ]    True if shell option “OPTIONNAME” is enabled.

[ -z STRING ]                True if the length of “STRING” is zero.

[ -n STRING ] or           True if the length of “STRING” is non-zero.

[ STRING ]

[ STRING1 == STRING2 ]     True if the strings are equal. “=” may be used instead of “==” for strict POSIX compliance.

[ STRING1 != STRING2 ]      True if the strings are not equal.

[ STRING1 < STRING2 ]       True if “STRING1” sorts before “STRING2” lexicographically in the current locale.

[ STRING1 > STRING2 ]       True if “STRING1” sorts after “STRING2” lexicographically in the current locale.

[ ARG1 OP ARG2 ]               “OP” is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true

                                      if “ARG1” is equal  not equal to, less than, less than or equal to, greater than, or greater than

       or equal to “ARG2”, respectively. “ARG1” and “ARG2” are integers.

[ ! EXPR ]                              True if EXPR is false.

[ ( EXPR ) ]                             Returns the value of EXPR. This may be used to override the normal precedence of operators.

[ EXPR1 -a EXPR2 ]              True if both EXPR1 and EXPR2 are true.

[ EXPR1 -o EXPR2 ]              True if either EXPR1 or EXPR2 is true.

The [ (or test) built-in evaluates conditional expressions using a set of rules based on the number of arguments. More information about this subject can be found in the Bash documentation. Just like the if is closed with fi, the opening square bracket should be closed after the conditions have been listed.

Commands following the then statement

The CONSEQUENT-COMMANDS list that follows the then statement can be any valid UNIX command, any executable program, any executable shell script or any shell statement, with the exception of the closing fi. It is important to remember that the then and fi are considered to be separated statements in the shell. Therefore, when issued on the command line, they are separated by a semi-colon.

In a script, the different parts of the if statement are usually well-separated.

Script -1 :

If any one  wanted to check a particular file exists or not.

The option called -f is used to check regular file .If file called messages is available  in /var/log if its available then it will print “/var/log/messages exists “.

if not then it prints  “/var/log/messages DO NOT exists.”

Give execute permission to a file.

Now execute the file.

Yes ….. The file is available at /var/log  so it prints the above message.

Script – 2: 

if the file is protected against accidental overwriting using redirection.

Give execute permissions

Execute the file.

Script -3 :

Testing exit status with if.

We executed directly if conditions here we  get the result as “Earlier command executed successfully”.

Script -4 :

Testing with a command and then $?

Here we found oracle user .

The same command we will use with if clause.

If grep command true then command will execute and it prints “user exists”

Working with numeric.

Create a variable and store the numeric value using “file.txt” file

The command it stores the filename so go with one more command

The below if clause prints “Condition is true” because the lines are greater than 4.

The below if clause prints “Condition is false” because the lines are not greater than 10.

Working with string comparisons.

The command “whoami” tell you which user you logged in into operating system.

If ORACLE is not equal to root then its prints following message.

“here $0 indicates bash”

Advanced IF usage

Checking command line arguments

Instead of setting a variable and then executing a script, it is frequently more elegant to put the values for the variables on the command line.

We use the positional parameters $1, $2, …, $N for this purpose. $# refers to the number of command line arguments. $0 refers to the name of the script.

Example with two arguments we passed.

we need to execute in debugging mode .we should pass two arguments

As per my height & weight its telling ” You should eat a bit more fat.”

As per my height & weight its telling “You should eat a bit more fruit.”

if/then/elif/else constructs

General

This is the full form of the if statement:

if TEST-COMMANDS; then

CONSEQUENT-COMMANDS;

elif MORE-TEST-COMMANDS; then

MORE-CONSEQUENT-COMMANDS;

else ALTERNATE-CONSEQUENT-COMMANDS;

fi

The TEST-COMMANDS list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. If TEST-COMMANDS returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding MORE-CONSEQUENT-COMMANDS is executed and the command completes. If else is followed by an ALTERNATE-CONSEQUENT-COMMANDS list, and the final command in the final if or elif clause has a non-zero exit status, then ALTERNATE-CONSEQUENT-COMMANDS is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

Example 1:

Complex variable and simple if.

Using following command i will get the largest space occupied mount point in size.

The above result is “42” that is largest space occupied mount point

Now will write a script to send alert if disk space is reached some of the value .

The variable “space” will have a value of largest disk size

The variable “alertvalue” have constant value called “80”.

In IF clause we written if space variable greater than equal to alertvalue then its sends alerts.

The output is “Disk space is normal” because its not reaches alertvalue.

Now we will set alertvalue =40

Execute :

Once its reaches alertvalue then its automatically sends alert message called “At least one of my disks is nearly full!”

Example : 2

with nested if clauses.

Execute the file.

Thank you ……

Note: Please test scripts in Non Prod before trying in Production.
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Add Comment