D C
D C

Reputation: 437

How to pass a nested command to function in a command line to ssh?

I have a script like the following:

#!/bin/bash
SERVER=127.0.0.1
ssh root@$SERVER << EOF
   checkcommand(){
      echo "checking $1"
      command -v $1 || apt install $1
   }
   checkcommand git
EOF

It won't work at all. How can I fix it?

Upvotes: 0

Views: 95

Answers (2)

Barmar
Barmar

Reputation: 780889

You need to prevent the variables in the here-document from being evaluated on the local system. You can make it act like a quoted string by putting the end token in quotes.

#!/bin/bash
SERVER=127.0.0.1
ssh root@$SERVER << 'EOF'
   checkcommand(){
      echo "checking $1"
      command -v $1 || apt install $1
   }
   checkcommand git
EOF

This is documented in the Bash Manual section on Here Documents:

If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ’`.

word refers to the token after <<, and delimiter refers to the matching token at the end of the here-doc.

Upvotes: 1

William Prigol Lopes
William Prigol Lopes

Reputation: 1889

You can use as follow:

ssh root@server command -v git || apt install git

Upvotes: 0

Related Questions