【问题标题】:shell script ambiguous redirect [duplicate]shell脚本不明确的重定向[重复]
【发布时间】:2013-04-15 06:25:58
【问题描述】:

我正在尝试创建简单的 shell 脚本来识别两个文本文件的输出之间的差异。当我重定向到文件(即 > a 和 > b)时,我能够成功运行脚本。

我在下面尝试将输出重定向到变量而不是文件以避免不必要的文件创建,但我收到错误ambiguous redirect

有人可以教我如何解决这个错误吗?

    sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/msmscgateway |grep "CIMD2:" | awk '{print $1, $2}' > $a
    sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/last/msmscgatewaylast |grep "CIMD2:" |awk '{print $1, $2}'  > $b
    echo="diff $a $b"

#echo "$DIFF"

test2.sh: line 2: $b: ambiguous redirect

我也尝试过其他方法,但得到不同的错误

$a=`sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/msmscgateway |grep "CIMD2:" |awk '{print $1, $2}'`
$b=`sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/last/msmscgatewaylast |grep "CIMD2:"|awk '{print $1, $2}'`
echo="diff <$a <$b"

test1.sh: line 1: =CSMSH3: command not found test1.sh: line 2: =CSMSH3: command not found

但在 shell 提示符下执行单个命令时工作正常

"sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/msmscgateway |grep "CIMD2:" |awk '{print $1, $2}'"

也在命令提示符下尝试过,但在脚本中失败

diff

【问题讨论】:

  • diff 只能接受一个文件作为参数,而你正在尝试比较两个不起作用的字符串
  • diff
  • diff
  • 不要重复自己。用于生成$a$b 的命令之间的唯一区别似乎是输入文件。不要让读者费力去意识到这个事实。重构代码,使其一目了然。

标签: shell redirect ambiguous


【解决方案1】:

您可以使用 command substitution

foo=$(sed 'bar' baz.txt)

process substitution

read foo < <(sed 'bar' baz.txt)

或者你可以使用 Bash 4.2 lastpipe

shopt -s lastpipe
sed 'bar' baz.txt | read foo

【讨论】:

    【解决方案2】:

    你的:

    sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/msmscgateway |grep "CIMD2:" | awk {print $1, $2}' > $a
    sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/last/msmscgatewaylast |grep "CIMD2:" |awk '{print $1, $2}'  > $b
    

    应该是:

    a=$(sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/msmscgateway |grep "CIMD2:" | awk '{print $1, $2}')
    b=$(sed -n '/eTopUp MU(55) Gateway Status1:/,/eTopUp MU(60) Gateway Status:/p' /root/scripts/last/msmscgatewaylast |grep "CIMD2:" |awk '{print $1, $2}')
    

    将输出放入变量中。现在它可能会抱怨,因为在您的情况下,$a$b 在扩展时不会转化为任何内容。

    但是正如有人提到的,这可能不适用于diff $a $b

    【讨论】:

    • 这在命令提示符下工作,但在脚本差异中失败
    • 它在sh 中失败,但在bash 中有效,因为它们不同。
    【解决方案3】:

    如果你不想的话,根本不需要变量(至少在 Bash 中):

    diff <(echo -e "a\nb\nc") <(echo -e "a\nc\nc")
    

    基本语法是

    diff <(CMD1) <(CMD2)
    

    【讨论】:

    • hi kjell diff
    • 您的脚本是 bourne 脚本 (#!/bin/sh) 吗?试试 bash (#!/bin/bash)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2013-12-21
    • 2016-10-29
    • 2015-09-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多