i use a simple function in a script in order to ckeck if a string contains a particular substring:
#!/bin/bash
#
subs() {
case $2 in
*$1*)
return 0 ;;
*)
return 1 ;;
esac
}
# example 1
res="$(grep -E '^blufoobla|^blubarbla' ~/test/file)"
subs foo "$res" || echo "blufoobla" >> ~/test/file
subs bar "$res" || echo "blubarbla" >> ~/test/file
# example 2
keym=us-whatever_foo
if subs - "$keym"; then
echo there
else
echo nope
fi
question 1: do i have to quote $1
in the case pattern of the function? unquoted variables in case patterns are interpreted as globs. therefore - i guess - there is no need to quote the variable in this particular case. but i'm not sure.. .
question 2: do i have to quote the first argument of the function ( subs foo "$res"
or subs "foo" "$res"
/ subs - "$keym"
or subs "-" "$keym"
.. ?
i want to avoid excessive quoting.
printf '%s' "foobarbla" | grep -Fq "bar"
?blufoobla bar
would match the grep and both the subs tests, and the script wouldn't add anything to the file, even thoughblubarbla
didn't already exist theregrep -Eo '^blufoobla|^blubarbla'
. concrete case: sshd_config in postinstall-script:grep -Eo '^PermitRootLogin no|^UseDNS no|^PasswordAuthentic.*no'
. put it in a variable and do thesubs
thing. this way, i have only 4 short and well-formed lines for this task (if i exclusively use grep or test or parameter expansion , the task looks bloated, less readable, less maintainable, resp. "out-of-form"). + there are 3 other cases for this function in the original script. i have to take a look at your answer now.