Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 1
    Namely, that's because the command substitution is in a double-quoted string, so it expands in the local shell, before ssh is launched, so the remote shell doesn't see a token there. If it was single-quoted so that the remote shell saw if $(...); then, it wouldn't be an error, but the exit status of the command inside the command substitution would be considered if it didn't output anything. Commented May 10 at 12:13
  • @ilkkachu Wow, OK, but why would anyone do it this way... Commented May 10 at 15:25
  • $( ... ) gets you the string value of the output not the exit status. if you want exit status do ( ) without the $ (but ( ) not needed between if and ;then ) Commented May 10 at 21:29
  • 1
    @Jasen, it expands to the output, yes, and usually the exit status of a command substitution isn't visible, e.g. in something like echo $(false), it's the exit status of echo that remains. But if there is no "main" command, then the exit status of the (rightmost) command substitution is used. Usually that would be an assignment, like if a=$(whatever); then do something with $a; fi, but it works without the assigment, try e.g. if $(false); then echo no; elif $(true); then echo yes; fi and variants. :) Commented May 11 at 15:52
  • 1
    if \$(whoami | grep -q root);then would not be enough to prevent it as there are 3 layers of shell interpretation here, the local shell, the shell started by sshd and the shell that su starts. As you want that code to be run by the latter, and double quotes are used everywhere, you'd need to escape that $ for both the local and remote shell. Commented May 11 at 17:51