Question

I have a problem that gaslights me.

Here comes my bash script "foo" reduced to the problem:

#!/bin/bash

function Args()
{
    [[ "$1" == "-n" ]] && [[ -d "$2" ]] && printf "%s\n" "new ${3}"
    [[ "$1" == "-p" ]] && [[ -d "$2" ]] && printf "%s\n" "page ${3}"
}

[[ $# -eq 3 ]] && Args "$@"
echo $?

Now when I execute this code, the following happens:

$ ./foo -n / bar
new bar
1

This, however, works:

$ ./foo -p / bar
page bar
0

Please, can anybody explain?

Sorry if this is a known "thing" and my googleing skills must be improved...

Was it helpful?

Solution

It is returning 1 in first case only because 2nd condition:

[[ "$1" == "-p" ]] && [[ -d "$2" ]] && printf "%s\n" "page ${3}"

won't match/apply when you call your script as:

./foo -n / bar

And due to non-matching of 2nd set of conditions it will return 1 to you since $? represents most recent command's exit status which is actually exit status of 2nd set of conditions.

When you call your script as:

./foo -p / bar

It returns status 0 to you since 2nd line gets executed and that is also the most recently executed one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top