[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: |
John Kearney |
Subject: |
Re: [Help-bash] How to use "&&" to replace "if" statement when "return" is used? |
Date: |
Sun, 5 May 2013 12:10:47 +0200 |
Am 21.04.2013 16:19, schrieb Peng Yu:
> Hi,
>
> I'm trying to use "&&" to replace "if". But the following shows that
> when "return" is used the replacement can not be done. Is there a way
> to use "&&" to replace "if" even "return" or "exit" is used?
>
> ~/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
>
> ~/linux/test/bash/man/operator/&&/return$ ./main.sh
> function cmd1 {
> [ '' ] && return 1
> }
>
> cmd1
> echo $?
> 1
>
> function cmd2 {
> [ x ] && return 1
> }
>
> cmd2
> echo $?
> 1
>
> function cmd1 {
> if [ '' ]
> then
> return 1
> fi
> }
>
> cmd1
> echo $?
> 0
>
> function cmd2 {
> if [ x ]
> then
> return 1
> fi
> }
>
> cmd2
> echo $?
> 1
>
> ~/linux/test/bash/man/operator/&&/return$ ./main_echo.sh
> function cmd1 {
> [ '' ] && echo 1
> }
>
> cmd1
>
> 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
>
>
>
the problem is you are only setting the return value on success, and on
error its the samme value as what you seem to want to return on success.
you could do something like
function cmd2 {
[ x ] && return 1 || return 0
}
or like
function cmd2 {
! [ x ]
}
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Re: [Help-bash] How to use "&&" to replace "if" statement when "return" is used?,
John Kearney <=