根据关键字执行bash命令

时间:2017-07-21 10:53:25

标签: bash

我试图为我的shell提供一个文件作为输入,作为回报,它应该测试文件是否包含特定的单词并决定执行什么命令。我还没弄清楚错误可能在哪里。请找到我写的shell脚本:

#!/bin/(shell)

input_file="$1"

output_file="$2"

grep "val1" | awk -f ./path/to/script.awk $input_file > $output_file

grep "val2" | sh ./path/to/script.sh $input_file > $output_file

当我输入使用awk的文件时,所有内容都按预期执行,但对于第二个命令,我甚至没有得到输出文件。任何帮助深表感谢 欢呼声,

1 个答案:

答案 0 :(得分:1)

您没有在问题中指明这一点,但我猜您有一个包含关键字的文件,例如:包含cmdfile的文件x-g301。然后你运行你的脚本:

./script "input_file" "output_file" < cmdfile

如果是这样,第一个grep命令将在搜索第一个模式时使用cmdfile上的整个stdin,并且第二个grep不会留下任何内容。这就是为什么第二个grep,然后是你的第二个脚本,没有输出。

有很多方法可以解决这个问题,但选择正确的方法取决于您的具体操作,以及cmdfile的外观如何。假设这是一个更大的文件而不仅仅是命令模式,你可以将该文件作为第三个参数传递给你的脚本,如下所示:

./script "input_file" "output_file" "cmdfile"

让你的脚本像这样处理它:

#!/bin/bash

input_file="$1"
output_file="$2"
cmdfile="$3"

if grep -q "X-G303" "$cmdfile"; then
    awk -f ./mno/script.awk "$input_file" > t1.json
fi

if grep -q "x-g301" "$cmdfile"; then
    sh ./mno/tm.sh "$input_file" > t2.json
fi

这里我还假设你的awksh脚本并不真正需要grep的输出,因为你给它们输入文件的名称。

请注意,使用grep进行存在搜索的正确方法是通过其退出代码(以及带有-q的静音输出)。而不是if我们可以使用短路(grep ... && awk ...),但这种方式可能更具可读性。

相关问题