1

I'm writing a bash script and I have a function that gets 3 arguments, a hostname, a command, and a file, it should excute the command on that hostname and redirect the output to the filename. This is the fucntion:

execmd ()
    {
    P_SERV="$1"
    P_CMD="$2"
    P_OUT="$3"

    X_SERV=`hostname`
    if [ "$P_SERV" = "$X_SERV" ] ; then
       $P_CMD >> $P_OUT
    else
       ssh $P_SERV $P_CMD >> $P_OUT
    fi
    }

When I execute:

execmd venus "cat /proc/meminfo" /tmp/meminfo

I get the error

cat /proc/meminfo: no such file or directory

any idea why its not working? same behavior either if call it with local hostname or remote hostname.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Marcelo
  • 11
  • 3
  • 3
    You're trying to run a command named `cat /proc/meminfo` with no arguments, not `cat` with the argument `/proc/meminfo`. – Satō Katsura Sep 13 '16 at 19:55
  • If `$P_CMD` isn't quoted, as in the code in the question, it should get word-split when the script runs the command. That should make your example `cat` command work as expected, and indeed the function works for me with `execmd $myhostname "cat /proc/meminfo" output`. – ilkkachu Sep 14 '16 at 08:06
  • However, a typo in the file name would show the error from `cat` on the terminal, since stderr isn't redirected, so with `execmd $myhostname "cat /proc/meminfox" output` I get `cat: /proc/meminfox: No such file or directory`. Looking closely at your error message, I think it might come from `cat`, but I suspect it's not copied correctly here: usually the `No` would be with an uppercase `N`. – ilkkachu Sep 14 '16 at 08:10
  • Also, the error message from bash would be `bash: catxx: command not found`. Though an older bash (3.1.17 tested) might scramble that if the command name contained a carriage return, but the error is still `command not found`. – ilkkachu Sep 14 '16 at 08:13
  • 2
    Check whether `/proc/meminfo` actually exists on the host that you are connecting to. I'm voting to close this as off-topic (typo/problem went away) until such time that the question is clarified about the existence of the file. – Kusalananda Mar 07 '19 at 14:08

1 Answers1

0

SSH executes a remote shell. To get consistent behavior for local execution, execute a local shell.

if [ "$P_SERV" = "$X_SERV" ] ; then
   sh -c "$P_CMD" >> "$P_OUT"
else
   ssh "$P_SERV" "$P_CMD" >> "$P_OUT"
fi

Don't forget double quotes around substitutions. For example, without double quotes, if P_CMD contains wildcards then they would be expanded locally in ssh $P_SERV $P_CMD.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175