Bash Script using Grep to search for a pattern in a file
The single quotes around $pattern
in the grep statement make the shell not resolve the shell variable so you should use double quotes.
Only one of those semicolons is necessary (the one before then
), but I usually omit it and put then
on a line by itself. You should put double quotes around the variable that you're echoing and around the variable holding your grep
pattern. Variables that hold filenames should be quoted, also. You can have read
display your prompt. You should use $()
instead of backticks.
read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
result=$(grep -i "$pattern" "$fname")
echo "$result"
fi