Testing your code on another file, it does actually work, even if it's a bit inefficient. Assuming that the /root/Turkiye.txt
file is a non-empty file that you have access to, the true
and false
calls, since they are the last commands to be executed in the function, sets the exit status of the function to either zero or non-zero.
It may simply be that you are entering strings into your script that can't be found as separate lines in the file you are reading. It's unfortunately unclear in the question what the file you are parsing looks like, what you are entering into your script and what you expect to get as a response from the script when doing so.
Note also that while read line
does not necessarily read lines from the input file. See e.g. "Understanding "IFS= read -r line"", and also that within [ ... ]
the operator that compares two strings is =
, not ==
.
You also need to double quote $keyboard
in your call to check
to avoid word splitting and filename generation (globbing).
It seems as if you want to use your function to determine whether the string read from the user occurs as a line in a particular file.
This could be done easier with
grep -qxF -e "$keyboard" /root/Turkiye.txt
This grep
command would search for the string in the given file and return a zero exit status (true) if a line is found that is exactly identical, and will otherwise return a non-zero exit status (false). The options used here are -q
to make grep
not output anything, -x
to compare full lines (not substrings) and -F
to do string comparisons (not regular expression matching). The -e
tells grep
that the next argument is the search pattern (an initial -
in the pattern would otherwise have been taken as introducing a command line option).
Your script, modified:
printf 'Please enter the value: ' >&2
IFS= read -r keyboard
if grep -qxF -e "$keyboard" /root/Turkiye.txt; then
echo 'yes'
else
echo 'no'
fi
Note that I output the prompt for the user to enter a string to the standard error stream. This is by convention and allows the output of the script to be redirected and used without it containing the prompt.
In bash
, you would have used
IFS= read -r -p 'Please enter the value: ' keyboard
(Note that bash
would output the prompt string to the standard error stream too when you use read -p
.)
If you would want to use the grep
in a function:
check () {
grep -qxF -e "$1" /root/Turkiye.txt
}
Then use
if check "$keyboard"; then
echo 'yes'
else
echo 'no'
fi
yes
if the file is empty.