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.

Mike Q
  • 6,716
  • 5
  • 55
  • 62
  • 1
    you may want to check -q option of grep also check this question for string contains check: http://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. – Kent Jan 11 '13 at 19:41

1 Answers1

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
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • +1 The main point is, don't use `grep` to do string operations that `bash` can do natively. – chepner Jan 11 '13 at 20:17
  • I would think that don't use regular expressions when glob patterns will do: `if [[ $file != *Trash* && $file != *home* ]]; then ...` – glenn jackman Jan 11 '13 at 22:09
  • Note that `[[ ... ]]` is a bashism; be sure to start your script with `#!/bin/bash` (or `#!/usr/bin/env bash`), not `#!/bin/sh` – Gordon Davisson Jan 12 '13 at 02:24