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'