D S
D S

Reputation: 129

if +/- plus number as a necessary condition

As a condition for the program I have to provide the value -number or +number. I would like to verify it and make sure it was entered correctly. How can I create a proper check rule?

Example:

if [ "$1" is -number ] || [ "$1" is +number ];then
    subsync -o "$1" "subtitle.srt"
fi

Upvotes: 1

Views: 99

Answers (3)

Toby Speight
Toby Speight

Reputation: 30931

A portable way to match patterns in shell is to use case:

is_plus_minus_number() {
   case "$1" in
       [-+]*[!0-9]*) return 1;;
       [-+]?*) return 0;;
       *) return 1;;
   esac
}

Demo:

for i in ++25 +25 -25 +-25 +25a 25 + -
do if is_plus_minus_number "$i"
   then printf '✓ %s\n' "$i"
   else printf '❌ %s\n' "$i"
   fi
done
❌ ++25
✓ +25
✓ -25
❌ +-25
❌ +25a
❌ 25
❌ +
❌ -

Upvotes: 1

denisrennes
denisrennes

Reputation: 26

This will ask the user to input either 14 or +14 or -14, will loop asking again if the user input was not correct, then the user input will be displayed.

NUMBER=14
 
user_input=
until [[ "$user_input" =~ ^[+-]?[0-9]+$ ]] && ( [ $user_input -eq $NUMBER ] || [ $user_input -eq $(($NUMBER * -1)) ] ); do
    read -p "input either $NUMBER or $(($NUMBER * -1)): " user_input
done
echo "user input:  $user_input"

Upvotes: 0

Cyrus
Cyrus

Reputation: 88889

With bash and a regex:

if [[ "$1" =~ ^[-+][0-9]+$ ]]; then

See: 4.1. Regular expressions and The Stack Overflow Regular Expressions FAQ

Upvotes: 1

Related Questions