【问题标题】:cat file_name | grep "something" results "cat: grep: No such file or directory" in shell scripting猫文件名 |在 shell 脚本中 grep "something" 结果 "cat: grep: No such file or directory"
【发布时间】:2015-04-21 20:26:06
【问题描述】:

我已经编写了从输入文件中读取命令并执行命令的 shell 脚本。我有这样的命令:

cat linux_unit_test_commands | grep "dmesg" 

在输入文件中。我在执行 shell 脚本时收到以下错误消息:

cat: |: No such file or directory
cat: grep: No such file or directory
cat: "dmesg": No such file or directory

脚本:

 #!/bin/bash

 while read line
 do
     output=`$line`
     echo $output >> logs
 done < $1

下面是输入文件(example_commands):

ls
date
cat linux_unit_test_commands | grep "dmesg"

执行:./linux_unit_tests.sh example_commands

请帮我解决这个问题。

【问题讨论】:

标签: linux bash shell


【解决方案1】:

您可能想知道为什么它不能与 cat 命令一起使用。 那么这里就是你问题的答案。

output=`$line` i.e. output=`cat linux_unit_test_commands | grep "dmesg"`

这里 cat 命令将 (linux_unit_test_commands | grep "dmesg") 所有这些作为参数,即文件名。

来自手册页:

语法: cat [OPTION]... [FILE]...

++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++

脚本没问题!

#!/bin/bash

while read line;
do
    output=`$line`
    echo $output >> logs
done < $1

要使其正常工作,您需要将 'cat: "dmesg": No such file or directory' 更改为 'grep "dmesg" linux_unit_test_commands'。它会起作用的!

cat linux_unit_test_commands

ls
date
grep "dmesg" linux_unit_test_commands

【讨论】:

    【解决方案2】:

    扩展变量后不解析|"等特殊字符;变量扩展后完成的唯一处理是分词和通配符扩展。如果要完整解析该行,则需要使用eval

    while read line
    do
        output=`eval "$line"`
        echo "$output" >> logs
    done < $1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2016-11-01
      • 1970-01-01
      相关资源
      最近更新 更多