All these examples use only builtin functions, and are completely compatible with dash
.
Finding Substrings
If you're actually looking for a substring of a string you can use case
or if
.
Let me illustrate by writing two different match
functions using each. If you're lazy you can cut/paste anyone of these functions into your script and use:
if match -32 "$STRING"; then
echo "found '-32'!"
fi
E.g. if you wanted to search for $SUBSTR
at both beginning and end, and separated from the rest of the string by spaces you could use something like this:
function match() {
local SUBSTR="$1" STR="$2" # get args
case " $STR " in # add extra spaces
*" $SUBSTR "*) return 0 ;; # return true if match
esac
return 1 # no match: return false
}
(In the above function I add space around $STR
so I don't have to explicitly look for matches at the beginning and end of the string.)
function match() {
local SUBSTR=" $1 " STR=" $2 " # get args + add extra spaces
[ "${STR#*"$SUBSTR"}" != "$STR" ] \
&& return 0 # match: return true
return 1 # no match: return false
}
This if
statement is a little trickier. The expression ${STR#*"$SUBSTR"}
part mean, take $STR
, and remove everything from the beginning of it, up to the first occurrence of $SUBSTR
(if $SUBSTR
couldn't be found, don't remove anything). Then we compare that with the original $STR
and if they are not the same, we know the substring was found.
Finding an argument
Now, if you're actually looking for an argument, you could use any of the above functions, and then simply use match "-32" "$*"
, but would find all substrings, and not distinguish the arguments from each other (e.g. in the unlikely event that any argument, such as a filename, happened to contain the string ' -32 ' that would match).
Better to just look at the args in that case. Again I'll write a little function for you that you can call with argmatch "$ARG" "$@"
argmatch() {
local FIND="$1" ARG; shift # get $FIND arg, remove it from $@
for ARG; do # loop $@
[ "$ARG" = "$FIND" ] && return 0 # found? then return true
done
return 1 # return false
}