【问题标题】:How to pass grep and echo combination command as if condition in shell script如何将 grep 和 echo 组合命令作为 shell 脚本中的条件传递
【发布时间】:2021-07-07 10:26:59
【问题描述】:

我在文件 finalinput.txt 中有如下一行

美国东部时间 2021 年 4 月 9 日晚上 10:52:35 c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b 1618023155272 我在下面写了一个小代码subtest.sh

keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"

for line in $(cat finalinput.txt)
do
if $line | grep "$keyinput" > /dev/null; then
 echo -e "$date $time\n" >> timeoutput.txt
fi
done

output :
 line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:35: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found
./subtest.sh: line 20: c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b: command not found
./subtest.sh: line 20: 1618023155272: command not found
./subtest.sh: line 20: ###Update: command not found
./subtest.sh: line 20: Assignment: command not found
./subtest.sh: line 20: Milestone: command not found
./subtest.sh: line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:37: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found

请在我错的地方帮忙

【问题讨论】:

  • 用shellcheck.net检查你的脚本
  • 试过了。它在这个 shellcheck 中显示不错,但在我的本地服务器上却是同样的错误
  • 你正在运行 $line 作为命令
  • 知道了.. 非常感谢如果 echo $line | grep "$keyinput"

标签: linux shell if-statement scripting grep


【解决方案1】:

你应该首先修复明显的 shellcheck 错误:

Line 1:
keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.
 
Line 3:
for line in $(cat finalinput.txt)
            ^-- SC2013: To read lines rather than words, pipe/redirect to a 'while read' loop.
 
Line 6:
 echo -e "$date $time\n" >> timeoutput.txt
          ^-- SC2154: date is referenced but not assigned (for output from commands, use "$(date ...)" ).
                ^-- SC2154: time is referenced but not assigned (for output from commands, use "$(time ...)" ).

在修复 SC2013 时读取 https://mywiki.wooledge.org/BashFAQ/001 。了解何时在 shell When to wrap quotes around a shell variable? 中使用引用。

我错了

$line 执行一个命令,其名称由变量 line 的扩展产生。您想将line 变量的内容作为输入传递给grep。你想要:

if echo "$line" | grep "$keyinput" > /dev/null; then

但最好是:

if printf "%s\n" "$line" | grep -q "$keyinput"; then

总体而言,在 bash 中您可以:

if grep -q "$keyinput" <<<"$line"; then

实际上,whle 脚本只是从文件中读取行......这就是 grep 所做的。

if grep "$keyinput" finalinput.txt; then

另外echo -e ....\n 与echo .... 相同。

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多