I have a bash script that's just a shortcut to the grep command. I call it like this:
stx -p /var/www -t 'my text'
This would run this command:
sudo grep -rinI /var/www -e 'my text'
I'm trying to add in the ability to include or exclude files with a certain extension (.css, .js, etc.). Here is the script:
#!/usr/bin/bash
#search for text in files
set -x #echo all commands
while [ -n "$1" ]; do
case "$1" in
-p) path="$2" # path to start search in
shift
;;
-t) txt="$2" # text to search for
shift
;;
-i) inc="$2"
#echo 'inc: ' $inc
include="--include=\*.${inc}" # file type to include
shift
;;
-?)
echo 'stx usage:'
echo '-p path to search in'
echo '-t text to search for'
exit 0
shift
;;
esac
shift
done
result=$(sudo grep -rinI $include "$path" -e "$txt")
echo "$result"
# grep options:
# r recursive
# i case-insensitive
# n show line number
# I ignore binary files
# --include only include files with specified extension
When I run this, for some reason it puts single quotes around the $include variable, so if I try to run this to search .js files for "my text":
stx -p /var/www -t 'my text' -i js
it produces this:
sudo grep -rinI '--include=\*.js' /var/www -e 'my text'
The single quotes around the --include*.js are breaking it. How can I stop it from inserting those quotes?
set -x
. Those quotes are just there to tell you that the entire string is being interpreted literally with no word splitting being performed. – jesse_b Oct 11 '19 at 18:31\
ininclude="--include=\*.${inc}"
– muru Oct 11 '19 at 18:33\*
to*
, and thegrep ... $include
togrep ... "$include"
. Someone may create a file named--include=hehe.js
just to mess with people running sudo from scripts. – Oct 11 '19 at 18:42ag
, ripgrep, ack-grep, and several similar projects. Why not just use one of these instead? Spend a few hours evaluating them and comparing their pros and cons. – cas Oct 12 '19 at 03:38