user1968965
user1968965

Reputation: 9

Argument checking in bash

I am trying to check the arguments that are passed into the script. It should have a minimum of 2 arguments and can have a maximum of 3. The 3rd argument if present should be "-I". I though I could do this but its not working.

if [  \( ! $# = 2 \) -o \( $# = 3 -a "$3" != "-I" \)  ];then
exit 0
fi

What am I doing wrong? Any suggestions on how to make it work?

Upvotes: 0

Views: 103

Answers (2)

Konza
Konza

Reputation: 2163

Try this

#!/bin/bash
MAX_ARGUMENTS=3
echo $#
if [ $# -eq $MAX_ARGUMENTS ]
then
    echo "hi"
    last=${!#}
    if [ $last == "-l" ]
    then
            echo "its l"
    else
            echo "its not l"
    fi
    else
    echo "bye"
fi

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881113

In bash, you can do something like this:

#!/bin/bash

if [[ $# -eq 3 ]] ; then
    if "$3" != "-I ]] ; then
        echo "Argument 3 must be '-I' if present"
        exit
    fi
fi

if [[ $# -ne 2 && $# -ne 3 ]] ; then
    echo "Needs two or three arguments"
    exit
fi

echo "[$1]"
echo "[$2]"
echo "[$3]"

Upvotes: 2

Related Questions