The answers already posted are certainly correct, but it may be worthwhile to note that occasionally parameter expansion can serve the same purpose with perhaps some additional flexibility.
% p() { printf 'notvar = %b\n' "${notvar##"${string1}"}${string2}" ; }
% string1='some stuff about things\c'
% string2='some different stuff maybe'
% notvar="$string1" p
> 'some different stuff maybe'
% notvar="$string2" p
> 'some stuff about things'
Ok, so the above isn't super-useful as is, but also consider that you can use the similar methods for testing variables in here-documents, in-line variable assignments if necessary (to a degree...), or even just as a shorter (and faster!) means of writing your first statement.
[ ! "${var##"string"}" ] && _MATCH || _NOMATCH
Or even...
[ ${#var#*"${s=string}"} -lt ${#var} ] && _SUB_STRING_TEST=TRUE
Possibly even...
% p() { printf '%s is %s of %s' "$2" "${var_chk-not}" "$1"
> }<<HEREDOC
> ${in="${1##*"${2}"*}"}
> ${in:-
> ${in="${1##"${2}"}"}
> ${in:-${var_chk=all}
> ${var_chk=some}
> }
> HEREDOC
%
[[ $var == "string" ]]
, which is POSIX, but optional (afaik). Or you use[ "$var" = "string" ]
. Note the""
around the variable in the single-bracket edition: it's required in case$var
is empty – Roche$var
as litb mentioned. Without the quotes,[ $var = "value" ]
becomes[ = "value" ]
which confuses the shell pretty horrendously. You will probably see an error like "[: =: unary operator expected" when you encounter an empty variable otherwise. – Bochum