LINUX CLASSES - PROGRAMMING
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.
Note: If you've never written or seen a computer program in your entire life, the rest of
this section will probably seem a bit foreign. But try to follow the examples; then
test and modify them on your own to get the hang of it.
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, and
not 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
[ RETURN TO INDEX ]
Comments - most recent first (Please feel free to answer questions posted by others!)
Dennis Korbinsky ( 06 Nov 2012, 21:19)
I like your website. Very good information. Thank you please.
Sam ( 24 Mar 2012, 01:04)
I need help with this.Can any one help?
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]
jayant ( 21 Feb 2012, 03:14)
Help me to get execute below commands daily
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
Kerman Mistry ( 15 Feb 2012, 23:57)
Hi Bob,
Your tutorial is a no non-sense; to the point tutorial. Thanks for a great
job.
AMR ( 06 Feb 2012, 10:58)
hardworker, look into cron
PS ( 31 Jan 2012, 04:52)
A unix script(ftp files) is running on unix server properly and produced
correct output but one workflow which contains same script is not working
while running on informatica power center server manually its showing
status as waiting but not succeded, could please tell me the cause of the
problem and solution for this
nordik_14 ( 28 Jan 2012, 04:48)
Very good tutorial. Im fortran programer and for my needs initialization in
bash is very useful.
Thanks from mexico
Raghunath Divekar ( 16 Jan 2012, 20:50)
Dear BOB, U have done a great job. Really good notes which helped me
revise all the commands I had used around 15 years back. You have made
Linux look like simple and easy.............
kashyap ( 16 Nov 2011, 02:37)
Hi,
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
Terry ( 18 Sep 2011, 05:19)
can someone please help me with a code for writing a script that shows
multiple files in the directory that exist and those that do not.
hardworker ( 30 Jun 2011, 03:45)
hi i need to write a perl script that checks for a file for 8 hrs..once 5
hrs over, it should send a mail that the file not came for every half
hour,at the same time the check for file should continue.
how can i do that?i should not use more loops for this!!
mahesh ( 11 Mar 2011, 00:26)
Write a pgm which test the command from commandline argument then report
whether it is directory or file. it is readable or writeable or executable
file in linux.
Brahma ( 28 Feb 2011, 02:11)
can any body telll me this....
q) Write a script that takes a numeric input from user and tell him if the
value is positive or negative or zero.
Russel ( 22 Feb 2011, 01:49)
Need Help:
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
Someone ( 10 Feb 2011, 23:15)
@Player: at 0 seconds, test interprets negative 1 (-1) as an option, and so
it needs a number to test. If you quote it, like this:
#!/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.
SSS ( 08 Feb 2011, 22:54)
u r really helpful
Rajiv ( 24 Jan 2011, 00:59)
Hi Gurus,
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.
Ren ( 13 Dec 2010, 12:29)
I need to test whether some string, (variable name of $string1) is found as
text inside a text file. If I read the file and find the string, then I
want to backup the filename.txt to filename.txt.bak, replace $string1 with
the value in $string2, create the new file filename.txt with the new text,
and leave filename.txt.bak as a backup of the original file.
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.
brian muchake ( 19 Nov 2010, 02:52)
Good effort
devi05dct@gmail.com ( 15 Nov 2010, 08:46)
Kindly help to create one script
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
Player ( 02 Nov 2010, 09:11)
when i execute the below script i get error:
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!!
Jay ( 25 Oct 2010, 11:31)
Hello Dr.Ravisankaar,
>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
Jay ( 25 Oct 2010, 11:29)
This page helped me too.
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
Renuka ( 25 Oct 2010, 03:30)
I want shell script for more and less command,for e.g.more act as less and
less act as more command.pls its urgent
Dr.Ravisankaar ( 05 Oct 2010, 22:02)
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
rics ( 24 Sep 2010, 11:20)
@Bob
thanks but i get this error message--
expr: non-numeric argument
here is the script:
tt1=23
tt1=`expr $tt1 - 1`
echo $tt1
Bob Rankin ( 24 Sep 2010, 10:50)
@rics - Try this
day1=`expr $day1 - 1`
rics ( 24 Sep 2010, 09:49)
can anyone help or point me to a good website. have not done shell
scripting for a long time, now find myself doing it again. need to do math
in the script ie. day1=24
want to change day1 to be 23
ie. day1=$day1 -1 does not work
what am i doing wrong ?
thanks
Richard ( 20 Sep 2010, 15:40)
What is the best syntax for comparing one variable to multiple values in an
IF statement.
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.
beginner ( 17 Sep 2010, 21:37)
Hi, i tried this
/* 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
Bob Rankin ( 16 Jul 2010, 15:07)
@hello_world - You might want to check the "Homework Helper" website. :-)
hello_world ( 16 Jul 2010, 00:44)
Write a program which will output greetings ( Good Morning, Good Afternoon,
Good Evening to user based on the time the script is run.
( Use case Statement in script)
Vishnu ( 09 Jul 2010, 00:59)
How to find the existence of similar files.. like files having a particular
date template
If [ -e *date* ] is giving error ,,too many arguments
ab ( 04 Jul 2010, 13:48)
why shell reverses the meaning of true or false compared to other
languages??
Kumar Piyus ( 21 Jun 2010, 11:25)
The information is to the point and very easy to understand. Really nice.
abhinav narain ( 09 Jun 2010, 12:16)
[ -z STRING ] option returns true,if the length of the string is zero
abhinav narain ( 09 Jun 2010, 09:10)
What is -z option used for ?
i cant find it in the websites i visited
George Lazarides ( 26 May 2010, 13:14)
Nice page! Your site is a great reference that I'll keep bookmarked for
future use!
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
Roberto ( 17 Apr 2010, 03:19)
VAR=$(COMMAND_LIST)
How I can test if the commands in COMMAND_LIST are run correctly?
Bob Rankin ( 18 Mar 2010, 20:49)
You are right! Fixed now.
Luis ( 18 Mar 2010, 18:32)
better if it was
if [ -r $1 -a -s $1 ]
not
if [ -r $1 -a -s $2 ]
right?
Pedro Oliveira ( 26 Feb 2010, 09:16)
Like it! It helped me on a shell script. Thanks!
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 Bob Rankin
- Privacy Policy
All rights reserved - Redistribution is allowed only with permission.