[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to use "&&" to replace "if" statement when "return"
From: |
Roman Rakus |
Subject: |
Re: [Help-bash] How to use "&&" to replace "if" statement when "return" is used? |
Date: |
Sun, 21 Apr 2013 21:17:12 +0200 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/17.0 Thunderbird/17.0 |
Hi. See comments below.
On 04/21/2013 04:19 PM, Peng Yu wrote:
Hi,
I'm trying to use "&&" to replace "if".
ok, but be very cautious. "&&" and "||"are operators of lists of
commands. See http://www.gnu.org/software/bash/manual/bashref.html#Lists
But the following shows that
when "return" is used the replacement can not be done.
It can be done. See below
Is there a way
to use "&&" to replace "if" even "return" or "exit" is used?
It is. You used it. But you don't understand return statuses. See below.
~/linux/test/bash/man/operator/&&/return$ cat.sh *
==> main.sh <==
#!/usr/bin/env bash
set -v
function cmd1 {
[ '' ] && return 1
}
cmd1
echo $?
function cmd2 {
[ x ] && return 1
}
cmd2
echo $?
function cmd1 {
if [ '' ]
then
return 1
fi
}
cmd1
echo $?
function cmd2 {
if [ x ]
then
return 1
fi
}
cmd2
echo $?
==> main_echo.sh <==
#!/usr/bin/env bash
set -v
function cmd1 {
[ '' ] && echo 1
}
cmd1
function cmd2 {
[ x ] && echo 1
}
cmd2
function cmd1 {
if [ '' ]
then
echo 1
fi
}
cmd1
function cmd2 {
if [ x ]
then
echo 1
fi
}
cmd2
Here we go.
~/linux/test/bash/man/operator/&&/return$ ./main.sh
function cmd1 {
[ '' ] && return 1
Return status of builtin command `[' is 1, command after && operator is
not executed.
}
Function returns without explicit `return' command, so it uses last
command's return status. It is `[' with return status 1.
cmd1
echo $?
1
This 1 return code is return code of function, which is in turn return
code of last command executed which is `['.
function cmd2 {
[ x ] && return 1
}
Similar as above. Return code of `[' is 0 so command after && is executed.
cmd2
echo $?
1
It used `return' command, but return status is also 1.
function cmd1 {
if [ '' ]
then
return 1
fi
}
See
http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs
Last command executed is `if' conditional statement. Return status is
described in the document and it is 0 in this case.
cmd1
echo $?
0
return status of `if'.
function cmd2 {
if [ x ]
then
return 1
fi
}
cmd2
echo $?
1
return status of `return' command.
~/linux/test/bash/man/operator/&&/return$ ./main_echo.sh
function cmd1 {
[ '' ] && echo 1
}
cmd1
The same for here.
function cmd2 {
[ x ] && echo 1
}
cmd2
1
function cmd1 {
if [ '' ]
then
echo 1
fi
}
cmd1
function cmd2 {
if [ x ]
then
echo 1
fi
}
cmd2
1
Hope it helps.
RR