Linux Shell Script Logic
(Where's the Logic in That?)
So far, all of our sample scripts have been just a sequence of commands executed one after the other. We haven't added any if/then/else logic or used looping constructs to control the flow of the program.Conditional Operations
Let's look at the if/then/else construct in a Bash shell script and see how to control the flow of a script with conditional logic. The general form of if/then/else is shown here, with the actual syntax shown in boldface and the parts you must supply in normal type:
if [ condition is true ]
then
execute these commands
else
execute those commands
fi
The else clause is optional, but you must end the construct with the fi command. You can also have nested if clauses by using the elif command like this:
if [ condition1 is true ]
then
execute these commands
elif [ condition2 is true ]
then
execute these commands
else
execute those commands
fi
So what kind of conditions can we test for? If you're dealing with numbers, here are the conditional expressions you can use. In other words, any of these expressions can go inside the brackets on the if or elif statement:
num1 -eq num2 True if num1 equals num2.
num1 -ne num2 True if num1 is not equal to num2.
num1 -lt num2 True if num1 is less than num2.
num1 -gt num2 True if num1 is greater than num2.
num1 -le num2 True if num1 is less than or equal to num2.
num1 -ge num2 True if num1 is greater than or equal to num2.
If you're comparing character strings, these are the valid conditional expressions:
str1 = str2 True if str1 and str2 are identical.
str1 != str2 True if str1 and str2 are not identical.
-n str1 True if str1 is not null (length is greater than zero).
-z str1 True if str1 is null (length is zero).
You can also test certain file conditions, such as whether or not files exist, the type of file, and so on. Here are the conditional expressions for files:
-f somefile True if somefile exists and is an ordinary file.
-d somefile True if somefile exists and is a directory.
-s somefile True if somefile contains data (the size is not zero).
-r somefile True if somefile is readable.
-w somefile True if somefile is writable.
-x somefile True if somefile is executable.
And finally, here are the logical operators, for performing tests that involve and, or, andnot conditions.
cond1 -a cond2 True if both cond1 and cond2 are true.
cond1 -o cond2 True if either cond1 or cond2 is true.
! cond1 True if cond1 is false.
Some if/then/else Examples
Here are some examples using the conditional expressions just listed. Note that the spaces on either side of the square brackets are not optional!
if [ $carprice -gt 20000 ]
then
echo 'Too rich for my blood.'
else
echo 'Can you get that model in blue?'
fi
if [ $maker = 'Buick' ]
then
echo 'Have you driven a Ford lately?'
fi
if [ -r $1 -a -s $1 ]
then
echo "The $1 file is readable and contains data."
fi
The case Statement
Bash provides a case statement that lets you compare a string with several possible values and execute a block of code when it finds a match. Here's an example of the case command, with the syntax shown in boldface and the parts you would supply in normal type:
case $1 in
-a)
commands;;
-f)
commands;;
*)
commands;;
esac
In this example, if the value of $1 was -a, the first block of commands would execute. If the value of $1 was -f, the second block of commands would execute. Otherwise, the third block of commands, following the asterisk clause, would execute. (Think of the asterisk as meaning "match anything.")
You can put as many commands as you need in place of commands in the sample, but be sure to end the block with a double semicolon. Only the first matching block of commands will execute in a case statement, and you must signal the end of the construct with the esac command.
Previous Lesson: Shell Script Variables
Next Lesson: Shell Script Looping
Comments - most recent first
(Please feel free to answer questions posted by others!)
Write a script (Linux or Windows) that takes two arguments, names of source and destination directories, and copies all files (including hidden) from source to destination, preserving the directory structure of the source directory.
If a user does not supply two arguments, a short help is displayed and the program quits.
If the source directory does not exist, an error is displayed on a screen, date, time, and nature of an error are added to a log file (ScriptFileName.log), and the program quits.
If the destination directory does not exist, it is created first.
If a file cannot be copied, your program should skip it and continue copying.
If a newer file exists in the destination directory, your program should skip it and continue copying.
If a newer file exists in the source directory, your program should silently overwrite an older file in the destination directory and continue copying.
Date, time, and full paths of the files copied are added to a log file, ScriptFileName.log upon completion.
Displayed help format:
Command syntax: ScriptFileName[src] [dst]
zcat b*20120220* | awk -F "\t" '$40 ~ /3:/' | cut -f 3,5,25,35,40 | grep -w D | grep -w M | cut -f 1 | grep 0:91 | cut -c 3-8 | sort | uniq -c | sort -r
I need o/p at path /home/smscsite/trace/bills_backup.d
Your tutorial is a no non-sense; to the point tutorial. Thanks for a great job.
Thanks from mexico
I would like to have a script which finds files less then 10MB and if there are no files then echo no files found using if loop.
thanks in advance
how can i do that?i should not use more loops for this!!
q) Write a script that takes a numeric input from user and tell him if the value is positive or negative or zero.
1. Write a shell program that takes one command line argument.
The program will do one of (a), (b), or (c) below:
(a) If the argument is missing or invalid:
print "XX: invalid or missing argument" on stderr and exit with 1
(where XX is the name of the shell program NOT hardcoded)
(b) If the argument is "more":
print the userids of all users who have a process running idle
for 2 days or more. Exits with 0
(c) If the argument is "less":
print the userids of all users who have a process running idle
for less than 2 days. Exits with 0
#!/bin/bash
count=$1
while [ "$count" -gt 0 ]
do
echo "$count seconds till supper time!"
count=$(expr $count - 1 )
sleep 1
done
echo "Supper time, YEAH!!"
exit 0
It should work.
I have a simple shell script as below,
sqlplus UN/pw@SID <<EOL
@Long_running_requests.sql
/
exit
EOL
I'm executing this shell script from command prompt for mailx -s to send the output of the .sql script. some times the SQL does not give any output depending on the where conditions which is an expected behaviour. But the mail is still sent with the SQL*plus connection details like below
*********************
SQL*Plus: Release 8.0.6.0.0 - Production on Mon Jan 24 14:18:55 2011
(c) Copyright 1999 Oracle Corporation. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production With the Partitioning, OLAP and Data Mining options
SQL> 32 SQL> Disconnected from Oracle Database 10g Enterprise Edition
SQL> Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
*************************
The requirement is to send a mail only when there is an o/p from the .sql. and no action required when the o/p is null.
Please suggest.
if [ NEED HELP HERE ]; then
mv filename.txt filename.txt.bak
sed s/string1/yyy/g filename.txt.bak filename.txt
endif
If the string is not found, then I want to do absolutely nothing. I do not want to backup the file nor create a new copy of the original file as there is no text that will change.
I need to check some particular packages installed in my os or not. (but i need to search for 4 package what shall i do)
rpm -qa | grep "htttpd* >file
script is below the error msg.
[root@CentOS_Vmware scripts_dir]# ./script5.sh 4
4 seconds till supper time!
expr: syntax error
./script5.sh: line 3: [: -gt: unary operator expected
Supper time!!, YEAH!!
#!/bin/bash
count=$1
while [ $count -gt 0 ]
do
echo $count seconds till supper time!
count=$(expr $count -1 )
sleep 1
done
echo Supper time!!, YEAH!!
>I have a problem. Pls. solve this
>I have to read set of lines from a file using >shell script. the lines are like this. I have to >read line by line. pls. help me
>
>chr18:3000-4000
>Chr20:5000-6000
grep -i chr /path/to/file
VAL=`dig nick.domain.com| egrep -A 1 CNAME| grep -v CNAME| awk '{print $5}'`
grep $VAL /etc/mail/access
if [ $? = 0 ]; then echo "Fine"; else echo -e "$VAL \t\t\t RELAY" >> /etc/mail/access;/usr/sbin/makemap hash /etc/mail/access.db < /etc/mail/access; fi
I have to read set of lines from a file using shell script. the lines are like this. I have to read line by line. pls. help me
chr18:3000-4000
Chr20:5000-6000
thanks but i get this error message--
expr: non-numeric argument
here is the script:
tt1=23
tt1=`expr $tt1 - 1`
echo $tt1
day1=`expr $day1 - 1`
want to change day1 to be 23
ie. day1=$day1 -1 does not work
what am i doing wrong ?
thanks
For example:
X can be equal to "ABC", "XY2", "XY3", "XY4", "XY5", "XY6" OR "ALG"
I want to do the SAME thing if x equals "XY2", "XY5", OR "XY6".
I know that I can use the following:
if [ (("$variable" == "XY2") -o ("$variable" == "XY5") -o ("$variable" == "XY6") ]
But, is there a shorthand?
For example, in SQL, I can write as follows to see if my variabe equals any of the values in the parentheses:
IF variable IN ("XY2", "XY5", "XY6")
Is there a neater way of writing this in Linux?
I am using #!/bin/sh. I am new to Linux. My thanks in advance.
/* in file ss1 */
if[$1 eq $2]
then
echo 'args are equal'
else
echo 'args not equal'
fi
/* i ran it as */
[bigfoot@localhost linux_work]$ ./ss1 2 2
/* the following warnings appears*/
./ss1: line 1: if[2 eq 2]: command not found
./ss1: line 2: syntax error near unexpected token `then'
./ss1: line 2: `then'
Please help.
Bob This is a wonderful website. THANKS
( Use case Statement in script)
If [ -e *date* ] is giving error ,,too many arguments
i cant find it in the websites i visited
But I think you forgot an option:
-e somefile True if somefile exists.
if [ -e /var/logs/error.log ]
then
echo 'There is an error log.'
else
echo 'No errors today.'
fi
How I can test if the commands in COMMAND_LIST are run correctly?
if [ -r $1 -a -s $1 ]
not
if [ -r $1 -a -s $2 ]
right?
I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But
don't ask me to send what you already have. :-) NO SPAM! If you post garbage, it will be deleted, and you will be banned.
Copyright © by -
All rights reserved - Redistribution is allowed only with permission.

