J.Mishra J.Mishra - 3 months ago 5
Bash Question

Shell script hangs forever grepping from file with name from "read $file"

I have my below shell script which searches for a string inside a file and returns the count. Not sure why it's getting stuck in the middle. Please can anyone explain.

#!/bin/bash

read -p "Enter file to be searched: " $file
read -p "Enter the word you want to search for: " $word

count=$(grep -o "^${word}:" $file | wc -l)
echo "The count for `$word`: " $count


OUTPUT:

luckee@zarvis:~/scripts$ ./wordsearch.sh
Enter file to be searched: apple.txt
Enter the word you want to search for: apple
^C

Answer

read needs to be passed a variable name. file, not $file.

#!/bin/bash

read -p "Enter file to be searched: " file
read -p "Enter the word you want to search for: " word

count=$(grep -o -e "$word" "$file" | wc -l)
echo "The count for $word: $count"

What was happening previously is that your file variable was empty, so your code was running:

count=$(grep -o "^${word}:" | wc -l)

...with no input specified, so it would wait forever for stdin.


By the way -- you don't need wc for this; grep can emit a counter itself, using the -c argument (also called --count in the GNU implementation). If you want that counter to go by words rather than lines, one can use tr to put each word on its own line:

count=$(tr '[[:space:]]' '\n' <"$file" | grep -c -e "$word")