Eugen Konkov
Eugen Konkov

Reputation: 25207

How to convert test operator from bash to sh?

I have next string comparison in bash:

if [[ $1 == "/"* ]]; then echo YES; else echo "$1"; fi

How to do same in sh?

Upvotes: 1

Views: 97

Answers (3)

tripleee
tripleee

Reputation: 189679

The case statement handles this elegantly.

case $1 in 
 '/'* ) echo YES;;
 *) echo "$1";;
esac

The lack of quoting before in and the general syntax with the double semicolons and unpaired right parentheses is jarring to the newcomer, but you quickly get used to it. It's quite versatile and much under-appreciated.

If you insist on using [ you could perhaps do something like

if temp=${1#?}; [ "${1%$temp}" -eq '*' ]; then
    ...

which uses a couple of parameter expansions to extract the first character of the variable; but case has glob pattern matching built in, so it's considerably more readable.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361909

You could do it with a case statement.

case $1 in
    /*) echo YES;;
    *)  echo $1
esac

The direct translation would be if [ "$1" = "/*" ], but it wouldn't work because sh doesn't support glob matches there. You'd need to invoke an external command like grep.

if printf '%s\n' "$1" | grep -e '^/' >/dev/null 2>&1; then
    ...
fi

This would be shorter with grep -q, but if you don't have bash then you may not have grep -q either.

Upvotes: 2

kvantour
kvantour

Reputation: 26501

If you would like to match a pattern, or regex in if statements if sh or fish you can use

if echo "$1" | grep -q ^/; then echo yes; else echo "$1"; fi

Upvotes: 0

Related Questions