As part of this script i need to be able to check if the first argument given matches the first word of the file If it does, exit with an error message; if it doesn't, append the arguments to the file. I understand how to write the if statement, but not how to use grep within a script. I understand that grep will look something like this

grep ^$1 schemas.txt

I feel like this should be much easier than I am making it.

I'm getting an error "too many arguments" on the if statement. I got rid of the space between grep -q and then got an error binary operator expected.

if [ grep -q ^$1 schemas.txt ]
then
        echo "Schema already exists. Please try again"
        exit 1
else
        echo "$@" >> schemas.txt
fi
Best Answer


grep returns a different exit code if it found something (zero) vs. if it hasn't found anything (non-zero). In an if statement, a zero exit code is mapped to "true" and a non-zero exit code is mapped to false. In addition, grep has a -q argument to not output the matched text (but only return the exit status code)

So, you can use grep like this.

if grep -q PATTERN file.txt; then
    echo found
else
    echo not found
fi

As a quick note, when you do something like if [ -z "$var" ]… , it turns out that [ is actually a command you're running, just like grep. On my system, it's /usr/bin/[ . (Well, technically, your shell probably has it built-in, but that's an optimization. It behaves as if it were a command). It works the same way, [ returns a zero exit code for true, a non-zero exit code for false. ( test is the same thing as [ , except for the closing ] )