Reputation: 149
I have tried upto my knowledge to get the result but i couldn't. I request you to guide me in a correct way.
Bellow is my bash script which is actually an init.d script.
#!/bin/bash
LOG_LEVEL="info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset"
CHECK_LOG_LEVEL=$2
logcheck() {
if [ ! -z $CHECK_LOG_LEVEL ]; then
if [ "$(grep -o "$LOG_LEVEL")" == "$CHECK_LOG_LEVEL" ]; then
echo "Starting the daemon with log_level"
else
echo "Check if the log-level argument name is correct!"
exit 1
fi
else
echo "Starting the daemon"
fi
}
case "${1}" in
start)
logcheck
;;
esac
exit 0
I want the grep to match the exact word. because of debug_rpc, debug_rpc_answer, debug_sql
if you user make a typo mistake by running script as: sudo /etc/init.d/myscript.sh start debug_rp
it need to display {echo "Check if the log-level argument name is correct!"}
I am trying to match exact user argument stored in variable $CHECK_LOG_LEVE with content $LOG_LEVEL
Any guidance or workaround for this..
Thanks.
Upvotes: 1
Views: 1282
Reputation: 247210
LOG_LEVEL="info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset"
CHECK_LOG_LEVEL=$2
# spaces below are very deliberate
if [[ " $LOG_LEVEL " != *" $CHECK_LOG_LEVEL "* ]]; then
echo "invalid log level" >&2
exit 1
fi
"debug_rp" will not pass that check, but "info debug_rpc" will, if someone is determined to provide invalid input
for exact matching, use an array:
LOG_LEVEL=( info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset )
CHECK_LOG_LEVEL=$2
found=false
for lvl in "${LOG_LEVEL[@]}"; do
if [[ $CHECK_LOG_LEVEL == $lvl ]]; then
found=true
break
fi
done
if ! $found; then
echo "invalid log level" >&2
exit 1
fi
Upvotes: 2
Reputation: 786091
You can use this grep -qw
(match word):
if grep -qw "$CHECK_LOG_LEVEL" <<< "$LOG_LEVEL"; then
echo "valid log-level argument"
else
echo "Check if the log-level argument name is correct!"
fi
Afterwards you can check return status using $?
Upvotes: 2