views:

52

answers:

2

Hi,

I'm having a hard time figuring out how to do this if statement. I want to do this:

IF (the function has only 1 argument AND $1 is a directory (in the current folder)) OR IF (the function has 2 arguments AND $1 is NOT a directory ) THEN

....

END

Sorry if it's not very clear,

Thanks in advance

A: 

You pretty much said what is needed in the question:

if [ $# = 1 -a -d "$1" ] || [ $# = 2 -a ! -d "$1" ]
then
    ...
fi

You can use other operators too - that will work in Bourne shell, let alone Korn or other POSIX shells (assuming that $# works correctly in a function - which it does in Bash).

fun()
{
    if [ $# = 1 -a -d "$1" ] || [ $# = 2 -a ! -d "$1" ]
    then echo "Pass ($1, $#)"
    else echo "Fail ($1, $#)"
    fi
}

fun $HOME
fun $HOME abc
fun $HOME/xyz abc
fun /dev/null
Jonathan Leffler
Note that you can use the '-o' operator in the test ('[') built-in; long-standing (but not necessarily still relevant) advice is to not try messing with both '-a' and '-o' (or, even, with either '-a' or '-o'). Doing things as shown is reliable and avoids the need to escape brackets (parentheses), etc.
Jonathan Leffler
Thank you, it works like a charm !
Selmak
A: 
if [[ $# == 1 && -d "$1" ]]; then
  echo "one param, first is a dir"
elif [[ $# == 2 && ! -d "$1" ]]; then
  echo "two params, first is not a dir"
else
  echo "unexpected"
fi
Roger Pate
I believe the OP wants "or" rather than `elif`.
Dennis Williamson
It's likely to want to do something (slighly) different in each case, which this shows in the example.
Roger Pate