linux - 停止发布 grep 消息

标签 linux shell posix

我正在编写一个带有 1 个字符串参数和一个文件的脚本。我想要这样,如果放入一个不存在的文件,它就会显示“文件名 无法读取”消息。

该部分确实有效,但它也显示“grep: grep.txt: No such file or directory”消息。如果第一个 if 语句为真,有什么方法可以阻止 grep 消息发布和结束脚本?

#! /bin/sh
if [ ! -f "$2" ]
then
    echo "$0" cannot be read 1>&2
fi

if [ $# -eq 2 ]
then
    grep "$1" $2
else
    echo there is more or less than 2 arguments 1>&2
fi

最佳答案

使用非零退出代码退出脚本以指示失败并阻止它继续执行 grep

if [ ! -f "$2" ]
then
    echo "$0" cannot be read 1>&2
    exit 1
fi

关于linux - 停止发布 grep 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58020247/

相关文章:

linux - 只接受 4 个字符长的十进制数字作为用户输入以供读取

linux - 自动递增变量名称

c - 什么是 C 中的 drand48() 默认种子?

c - 使用文件描述符打开读取文件

c++ - 使用 CreateProcess 尽可能使用单个命令参数调用 exec* 函数

linux - 使用指针在x86 Assembly中返回结果

linux - 如何在 C++ 中正确链接 .so 库?

linux - Bash - 管道多个 grep 并打印输出

linux - crontab 中的 cron 作业不工作

linux - 只得到grep : get ip of ifconfig的第一部分