2

I'm writing a bash script that is intended to execute some command, and depending on some flag, this command should be either executed locally or remotely. This command's output should be redirected to some file, and this file should be on the box that executes the command, that is, on the remote box if the command is executed remotely.

I'm trying things like

#!/bin/bash

REMOTE=1
function f
{
        CMD="$@"
        if [ "${REMOTE}" == "1" ]
        then
                ssh some_host "$CMD" 
        else
                $CMD 
        fi
}

# This executes "echo huhu" remotely and redirects the output into "out" on the remote box.
REMOTE=1 f echo huhu \> out

# This executes "echo haha > out" remotely (without redirection).
REMOTE=0 f echo haha \> out

When I don't escape the > sign, any output of f is redirected to "out" on the local box, of course.

How could I avoid this behavior?

2 Answers 2

1

Don't use eval; use arrays instead. And a solution for the SSH command.

1

Write eval $CMD instead of $CMD. When $CMD is expanded the interpretation of redirection has already happened and redirections operations will simply passed as ordinary arguments.

2
  • eval $CMD is buggy -- even if your command string is accurate, that string will be split into arguments and pieced back together again before it's run, which can break it. eval "$CMD" at least avoids that, even though it's far from ideal. Sep 14, 2017 at 23:06
  • As an example you can verify, set space=' '; CMD=$'printf \'%s\\n\' "tab\there" "three spaces here: <'"${space}${space}${space}"$'>"', and compare eval $CMD and eval "$CMD" -- you'll see their results differ. Sep 14, 2017 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.