I'm on it since days, I need to check for an user $1 if an Environnement Variable $2 exists.

I tried some cases :

 $ [[ -v a ]] && echo "a ok" || echo "a no"
 a no
 $ [[ -v $HOME ]] && echo "a ok" || echo "a no"
 a no 

(So nope (I tried on Bash > 4.2))

if [ su - ${1} -c "[ -z "${2}" ]" ]

Now, I'm trying this approach because I don't find what's wrong :/ !

su - root -c "echo "$HOME" | wc | cut -d' ' -f2"
su - root -c "echo "$HOME" | wc | sed 's/ //g'"
share|improve this question
up vote 0 down vote accepted

The syntax in your first examples is incorrect. If you write:

[[ -v $HOME ]]

Then you are actually executing the command:

[[ -v /home/yourusername ]]

Which of course is going to fail. You want:

[[ -v HOME ]] && echo ok || echo no

You can combine that with su to get:

su - root -c "[[ -v HOME ]]" && echo ok || echo no

Your last examples won't work because you can't nest quotes, and because shell variable expansion happens before command execution. That is, given:

su - root -c "echo "$HOME" | wc | cut -d' ' -f2"

The command you execute is actually going to be:

su - root -c 'echo /home/somesuser | ...'

If you want the value of $HOME from the perspective of root, you would need to prevent variable expansion in the local shell, for example by using single quotes:

su - root -c 'echo $HOME | ...'

It's not clear to me why you're passing the output to wc, because the word count of $HOME is almost always going to be 1. Rather than post-processing the output of wc with sed or cut, you can just use the -w option to get the word count:

su - root -c 'echo $HOME | wc -w'
share|improve this answer
    
Thanks for the answer. Sure, I always forgot to escape my var... Sry. su - root -c "[[ -v HOME ]]" && echo ok || echo no Doesn't work $ su - root -c "[[ -v HOME ]]" && echo ok || echo no -sh: -c: line 0: conditional binary operator expected -sh: -c: line 0: syntax error near HOME' -sh: -c: line 0: [[ -v HOME ]]' For su - root -c 'echo $HOME | ...' I took the habit to escape the var like that su - root -c "echo \$HOME | ..." I don't know which one is the best practice. And omg I didn't think about wc -w ! It does what I wanted to ! Thx – Chuck Noxis Oct 28 '16 at 13:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.