简体   繁体   中英

how to do if statements with “and” in sh

I try to solve this problem with the sh and not the bash. All i want is a if statement that check some regex AND something else. Normally in bash this would be an easy job but with the sh i only find solutions online that wont work for me

First thing i want to check:

if echo "$1"| grep -E -q '^(\-t|\-\-test)$'; 

Than i want to check:

if echo "$#"| grep -E -q '^(1|2)$';

Combined:

if [ \(echo "$1"| grep -E -q '^(\-h|\-\-help)$'\) -a \(echo "$#"| grep -E -q '^(1|\2)$'\) ];

ERROR:

grep: grep: ./analysehtml.sh: 41: [: missing ]
Invalid back reference
(echo: No such file or directory
grep: 1: No such file or directory

I also try many diffrent combinations with this brackets but non of them worked for me. Maybe someone can help me here :)

logical and between commands is &&

if 
    echo "$1"| grep -E -q '^(\-h|\-\-help)$' &&
    echo "$#"| grep -E -q '^(1|\2)$';

By default the exit status of a pipe is the exit status of last command.

set -o pipefail the exit status is fail if if any command of pipe has a fail exit status.

when only the exit status of the last command of a sequence must be checked

if { command11; command12;} && { command21; command22;};

However to check parameters there is no need to launch another process grep with a pipe there's an overhead.

Consider using following constructs work with any POSIX sh.

if { [ "$1" = -h ] || [ "$1" = --help ];} &&
    { [ $# -eq 1 ] || [ $# -eq 2  ];};

EDIT: Following are not POSIX but may work with many shell

if [[ $1 = -h || $1 = --help ]] && [[ $# = 1  || $# = 2 ]];

Works also with bash with set -o posix

也许对于您的特定情况,模式匹配可能会更好:

if [[ $1 =~ ^(\-h|\-\-help)$ && $# =~ ^(1|\2)$ ]]; then

The problem with your command is that the part within test or [ command is expression , not commands list .
So when you run [ echo 'hello' ] or [ \\( echo 'hello' \\) ] complains error in spite of sh or Bash . Refer to the classic test usage: The classic test command

And the syntax of if is:

if list; then list; fi

So you can just combine command with && operator in if statements:

if echo "$1"| grep -E -q '^(\-h|\-\-help)$' && echo "$#"| grep -E -q '^(1|\2)$'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM