Search code examples
linuxshellposix

Stop grep message from posting


I am working on a script that take 1 string argument and a file. I want it so that if a file is put in that doesn't exist, then it will display the "filename cannot be read" message.

That part does work however it also displays a "grep: grep.txt: No such file or directory" message. Is there any way to stop the grep message from posting and ending the script if the first if statement is true?

#! /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

Solution

  • Exit the script with a non-zero exit code to indicate failure and stop it from continuing on to the grep.

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