2

I have a script that I need to execute through ssh as another use, is there a way to pass whole script like this:

ssh -t user@server.com sudo -u user2 sh -c << EOF
 cd /home
 ls
 dir=$(pwd)
 echo "$dir"
 echo "hello"
 ....
EOF

Returns: sh: -c: option requires an argument

ssh'ing and sudo'ing separately is not an option and putting .sh file directly on the machine is not possible.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Anton Kim
  • 879
  • 13
  • 36

1 Answers1

5

sh -c requires a command string as the argument. Since you are reading the commands from standard input (through heredoc), you need to use sh -s option:

ssh -t user@server.com sudo -u user2 sh -s << 'EOF'
 cd /home
 ls
 dir=$(pwd)
 echo "$dir"
 echo "hello"
 ...
EOF

From man sh:

-c

string If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

-s

If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.

Need to quote the heredoc marker to prevent the parent shell from interpreting the content.

codeforester
  • 39,467
  • 16
  • 112
  • 140