Home > Software engineering >  Bash check arg value
Bash check arg value

Time:10-30

I have a script where I pass a string variable. Now I would like to check the value of the variable passed like this:

  1. Check if it's not null
  2. Check if is "Test1"
  3. Check if is "Test2"

I wrote this: #!/bin/bash

if [[ "$1" == "" || "$1" != "Test1" || "$1" != "Test2" ]]; then
    echo "ERROR: no argument or bad argument passed. Only Test1 or Test2 is accepted"
    exit 2
else
    echo "ok good value"
    exit 0
fi

but when I try the script (./script.sh Test1 or ./script.sh Test2) I receive always:

ERROR: no argument or bad argument passed. Only Test1 or Test2 is accepted

CodePudding user response:

thanks for your support, but it's wrong, because accept all values not null.

I solved using this:

if [[ "$1" != "Test1" ]] && [[ "$1" != "Test2" ]]; then

CodePudding user response:

Instead of if [[ ..., try case which is more portable:

case "$1" in 
    Test[12]) echo "ok good value"
              exit ;;
    *)        echo "ERROR: no argument or bad argument passed. Only Test1 or Test2 is accepted";
              exit 2 ;;
esac

Note: if a program has many users vague error messages of the form "No X or else no Y" can sometimes waste man-years of collective time, because half the users will be testing for the wrong problem. So if the code had a lot of users, separate error messages would be better:

case "$1" in 
    Test[12]) echo "ok good value"
              exit ;;
    "")       echo "ERROR: no argument passed. Only Test1 or Test2 is accepted";
              exit 2 ;;
    *)        echo "ERROR: Bad argument, only Test1 or Test2 is accepted";
              exit 2 ;;
esac

CodePudding user response:

Try replacing

if [[ "$1" == "" || "$1" != "Test1" || "$1" != "Test2" ]]; then

with

if [ -z "$1" ] || [ "$1" == "Test1" ] || [ "$1" == "Test2" ]]; then
  • Related