0

I'm using Debian 10. There is a command I run frequently to search for text.

sudo grep -rin <path> -e <text to search for>

Since I use this command often, I wanted to create a simple script to automate part of it and call it like this:

stx -p <path> -t <text to search for>

so I could call it like this:

stx -p /var/www -t 'navbar ul'
stx -p ~/.wine/drive_c/Program\ Files -t 'asdf ghjk'

The path and search text could potentially contain spaces, which is causing me problems for how to handle the quotes and escaping. The script:

#!/usr/bin/bash
#search text
while [ -n "$1" ]; do
        case "$1" in
                -p) path="$2" # path to start search in
                shift
                ;;
                -t) txt="$2" # text to search for
                shift
                ;;
        esac
        shift
done

echo sudo grep -rin $path -e \'$txt\'
#exit 0

sudo grep -rin $path -e '$txt'

#       grep options:
#       r       recursive
#       i       case-insensitive
#       n       show line number

In the echo the command looks to be right., but when I run this I am experiencing different problems with the path and the text part. The path part doesn't seem to work for filenames with spaces, and the text part seems to be searching for each word separately.

raphael75
  • 673
  • 9
  • 22
  • 2
    ALWAYS double-quote variables when you use them. So `sudo grep -rin "$path" -e "$txt"`. – roaima Sep 13 '19 at 12:17
  • It looks like that fixed it! Could you please add this as the answer? I can't believe it was that simple. :) – raphael75 Sep 13 '19 at 12:20
  • 2
    see [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters) – cas Sep 13 '19 at 12:31
  • 1
    See also [When is double-quoting necessary?](https://unix.stackexchange.com/questions/68694/when-is-double-quoting-necessary) (you seem to have used it in a couple of places where it isn't - and not where it really is) – steeldriver Sep 13 '19 at 12:44
  • Thanks so much for all the links! – raphael75 Sep 13 '19 at 13:26

1 Answers1

2

The issue was not double quoting variables.

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'.

See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

Gilles Quénot
  • 31,569
  • 7
  • 64
  • 82