jeffpkamp
jeffpkamp

Reputation: 2866

Bash test variable and program exit in same statement

I am trying to test if certain variables are set and if ping exits with 0. When I do

var=1 #set for later

#"If" checks exit status correctly

if ping -c 1 an-inaccessible-thing
then 
    echo T
else 
    echo F
fi

#returns  F

#"if" does not like the program in the [[ ]]
if [[ -n $var && ping -c 1 an-inaccessible-thing ]]
then
    echo T
else 
    echo F
fi

#returns this error for obvious reasons
-bash: conditional binary operator expected
-bash: syntax error near `-c'


#if runs its test on the output of the shell, not its exit code.  

if [[ -n $var && $(ping -c 1 an-inaccessible-thing) ]]
then 
    echo T
else 
    echo F
fi

#returns T, probably because it's being evaluated with -n and no the exit code

how can I test programs exit code inside the double square brackets?

Upvotes: 0

Views: 39

Answers (1)

KamilCuk
KamilCuk

Reputation: 141145

Because [[ is a separate (bash builtin) program, like ping or any other program.

Do && outside of [[ ]].

[[ -n $var ]] && ping -c 1 an-inaccessible-thing

Upvotes: 2

Related Questions