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.

5

1 Answer 1

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

You must log in to answer this question.

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