0

In bash I am often checking the value of a variable, is it OK that it do it this way ? Is there a better way?

Example:

    if [ "`echo ${file} | grep -vE '(Trash|home)'`" ] ;then

Which is checking that the variable file does NOT contain the words Trash or home, if it does not then do something. The point is that I'm using echo and grep, probably wasteful I assume.

Another example:

    if [ "`less ${TEMPQUERY} | grep 'http'`" ] ;then

Which is checking a file for the string http, if it is in the file, do something.

I guess I'm just wondering what other people do and if there is some strong reason why I should not be coding things in such a way. Anyway, Thank you in advance for you time.

1
  • 1
    you may want to check -q option of grep also check this question for string contains check: stackoverflow.com/questions/229551/string-contains-in-bash for file check, you don't need less, just grep -q 'http' file and read the return value. Commented Jan 11, 2013 at 19:41

1 Answer 1

5
$ file="My home"
$ [[ $file =~ Trash|home ]] ; echo $?
0
$ file="root"
$ [[ $file =~ Trash|home ]] ; echo $?
1

$ cat input.txt
http://...
$ grep -v -q http input.txt ; echo $?
1
Sign up to request clarification or add additional context in comments.

3 Comments

+1 The main point is, don't use grep to do string operations that bash can do natively.
I would think that don't use regular expressions when glob patterns will do: if [[ $file != *Trash* && $file != *home* ]]; then ...
Note that [[ ... ]] is a bashism; be sure to start your script with #!/bin/bash (or #!/usr/bin/env bash), not #!/bin/sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.