0

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'"

1 Answer 1

0

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'
1
  • 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 Commented Oct 28, 2016 at 13:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.