1838124 Members
4282 Online
110124 Solutions
New Discussion

Shell Script Help

 
SSP_1
Regular Advisor

Shell Script Help

Hi ,

I have a shell script written , having 2 nos of commnads to execute. Here I have to define a condition for the execution so that if the first command is successful then only second will get executed.

Pl help !!!!

Obstacles exist to challenge you to keep going. Not to quit.
9 REPLIES 9
Deepak Extross
Honored Contributor

Re: Shell Script Help

command1 && command2

command 2 will only get executed if command 1 is successful. See man sh-posix for details.
Sukant Naik
Trusted Contributor

Re: Shell Script Help

Hi Sripad,

Do something like this.

#!/usr/bin/ksh
command1
if [ $? -eq 0 ]
then
command2
fi


Who dares he wins
Deepak Extross
Honored Contributor

Re: Shell Script Help

Or you could try the more readable form:
command1
if [ $? -eq 0 ]
then
command2
fi
John Palmer
Honored Contributor

Re: Shell Script Help

Another way is:-

if command1
then command2
fi

Regards,
John
SSP_1
Regular Advisor

Re: Shell Script Help

Hi ,

In "if [$# -eq 0] then" what does "0" corresponds? I believe it's "false" so doesn't this condition mean "if exit status of my previous commnad is "false" then execute second one".

OR should I have to specify "1" instead of "0".
Obstacles exist to challenge you to keep going. Not to quit.
Deepak Extross
Honored Contributor

Re: Shell Script Help

In unix, a return value of 0 indicates success.
So [ $? -eq 0 ] is a test of successful execuation of the preceding command.
Deepak Extross
Honored Contributor

Re: Shell Script Help

Peter Kloetgen
Esteemed Contributor

Re: Shell Script Help

Hi,

this is very easy, you even don't need to test anything like return code:

first_command && second_command

--> second command will only be executed, if first command has a return code value of zero

first_command || second_command

--> second command is only executed, if first command was not successful, has a return code not equal zero.

If second command is executed later in the script, you have to put the return code of first command as value into a variable, cause return code is overwritten each time, a new command is executed:

first_command

var=`echo $?`

Then, if the second command has to be executed, check out the return code of the first command:

if [ $var -eq 0 ]
then
second_command
fi

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
V. V. Ravi Kumar_1
Respected Contributor

Re: Shell Script Help

hi,

u can check the success or failure of the command, include an echo statement.

when a command successfully executes "echo $?" should show "0" else it shows "1".

in ur case

command1
if [ $? -eq 0 ]
then
command2
fi

regds
ravi
Never Say No