字符串组装命令的 IO 重定向

发布于 2024-12-10 05:51:01 字数 669 浏览 0 评论 0原文

我正在编写一个 bash 脚本,旨在执行某些命令,并且根据某些标志,该命令应该在本地或远程执行。该命令的输出应重定向到某个文件,并且该文件应位于执行该命令的机器上,也就是说,如果该命令是远程执行的,则应位于远程机器上。

当然,我正在尝试类似

#!/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

当我不转义 > 符号时, f 的任何输出都会重定向到本地框上的 "out"

我怎样才能避免这种行为?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

洒一地阳光 2024-12-17 05:51:01

编写 eval $CMD 而不是 $CMD。当 $CMD 展开时,重定向的解释已经发生,并且重定向操作将简单地作为普通参数传递。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文