Search code examples
bashgrepquotes

Preserving (reconstructing?) single quotes in Bash arguments to script commands


I wrote a shell script that lets me grep through a directory tree and preserve the path in the grep output. It started out like this:

#!/bin/bash
# findjs.sh
# Given a word or argument, greps javascript files from one dir down to the 8th dir down,
# as in: */*.js */*/*.js ... */*/*/*/*/*/*.js 

f="*/*.js"
for p in {1..8}
do
    echo 'Searching '"$f"
    grep -in $1 $f;
    f="*/"$f
done

Works quite well. Problem is if I want to send a multi word string as my search term it expands them. This is OK:

./findjs.sh  aword /var/local/somedir

This is not:

./findjs.sh  'the message' /var/local/somedir

Bash devolves the grep line to

grep -in the message /var/local/somedir

I have tried all kinds of things to try and wrap $1 in single quotes like this:

escaped="'\''"
t=$escaped$1$escaped

or

grep -in $escaped$1$escaped $fp;

and single quotes in double quotes, etc etc. but single quotes disappear every time.

What am I missing?


Solution

  • grep "$1" ...
    

    ... should work just fine