Score:0

Function expand ssh execution

vu flag

As part of a script which runs on another (backup) server I'm trying to write a function which executes random commands remotely via ssh. To keep things simple, I want to keep the existing code mostly as is.

An example what I'm trying to do:

function NC_SSH_CMD () {
   cmdArgs=("$@")
   ssh -i [email protected] "bash -s" < ${cmdArgs[@]}
}

NC_SSH_CMD sudo -u "${webserverUser}" php ${nextcloudFileDir}/occ maintenance:mode --on

Basically, I want to use NC_SSH_CMD as a prefix for commands which should be run remotely via ssh. Thus the arguments passed should be treated as a remote command with arguments. Though my usage of cmdArgs as an array is the wrong way. It throws the error:

${cmdArgs[@]}: ambiguous redirect

What's the correct way to pass the command to the function and execute it?

Edit:

There was a bug with the command itself which was unrelated to the question. Since the error was unintuitive I didn't catch it. This works. But is there a better way to handle passing the string to the command?

function NC_SSH_CMD () {
   $(ssh [email protected]  "$*")
}
Score:1
hr flag

The < operator redirects the contents of a file via standard input. To redirect a string in bash you'd use a here string:

function NC_SSH_CMD () {
   cmdArgs=("$@")
   ssh -i path/to/identityfile [email protected] "bash -s" <<< "${cmdArgs[@]}"
}

Remember to quote the array expansion ${cmdArgs[@]} else its elements will be subject to word splitting and possible filename generation.


Note that unless ${cmdArgs[@]} needs to be run in a bash shell specifically, and you know that the remote root shell is something other than bash, you may as well omit the bash -s and pass the expanded argument list directly to the default remote shell, as you discovered. However you should use "${cmdArgs[@]}" (or "$@") in place of "$*" since the latter concatenates the arguments to a single string instead of passing them separately:

function NC_SSH_CMD () {
   ssh -i path/to/identityfile [email protected] "$@"
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.