3

I want to search a string in a file, and after much searching this website, I ended up using grep in and if statement. However, things aren't working as I expect them, even though I followed all the instructions I found on other related posts. Here's my code.

echo "Enter dicounter number"
read string1
echo "Enter side with LEDs"
read string2

if grep -q "dicounter_$string1_from_$string2" MasterFile.txt; then
   echo "dicounter_$string1_from$string2 already exists in MasterFile."
else
   { (a bunch of stuff to make the transmitter operate) }
fi

The primary problem I think is with the way I am reading in my command line arguments.

0

1 Answer 1

8

If a script is not working as you expect it to, one of the first things you might want to try is adding set -x before the troublesome spot in the code (in this case, before the grep), and running the script. You will then see what the script is actually doing, so that you can compare that to what you expect it to be doing.

In your case, the problem may be that _ is a valid character in variable names, so you are attempting to use value of $string1_from_ rather than $string1 as you expect. This is why it is a good practice, even if not using fancy manipulations, to enclose your variable names in curly braces. For example:

if grep -q "dicounter_${string1}_from_${string2}" MasterFile.txt; then
   echo "dicounter_${string1}_from${string2} already exists in MasterFile."
else
   [..]
6
  • A follow up question: After a while, the MasterFile.txt will have thousands of entries. Do you recommend a faster/more efficient way of searching for the strings?
    – Ptheguy
    May 31, 2017 at 16:06
  • @Ptheguy Using grep - q is already very fast, as it will quit as soon as it finds a match. The other thing you may try is to make the pattern more specific. This may possibly be done by anchoring the pattern to the beginning and/or end of the line (I haven't benchmarked to see if this actually makes a difference).
    – Kusalananda
    May 31, 2017 at 16:15
  • You can use grep -ql, which will stop at the first match rather than proceeding through the rest of the file.
    – DopeGhoti
    May 31, 2017 at 16:15
  • 2
    A syntax highlighting editor would also be a good tool to spot issues like this, though it might be that they'll just highlight the whole quoted string with one color. shellcheck.net warns about unset variables, though...
    – ilkkachu
    May 31, 2017 at 17:04
  • 1
    vim seems to DTRT: i.imgur.com/4QJwi88.png Also, you can set -u to make referencing an unset or undeclared variable an error condition which will cause the script to terminate.
    – DopeGhoti
    May 31, 2017 at 17:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .