字符串组装命令的 IO 重定向
我正在编写一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
eval
;使用 数组 代替。以及SSH 命令的解决方案。Don't use
eval
; use arrays instead. And a solution for the SSH command.编写
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.