lundi 10 février 2020

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?

Aucun commentaire:

Enregistrer un commentaire