How to negate an if condition in a Bash if statement? (if not command or if not equal) To negate any condition, use the ! operator, for example: if ! <test-command>; then <command-on-failure>; fi .
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.
You had it right, just put a space between the !
and the [[
like if ! [[
You can also put the exclamation mark inside the brackets:
if [[ ! $PATH =~ $temp ]]
but you should anchor your pattern to reduce false positives:
temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]
which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.
the safest way is to put the ! for the regex negation within the [[ ]]
like this:
if [[ ! ${STR} =~ YOUR_REGEX ]]; then
otherwise it might fail on certain systems.
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
(Source)
I like to simplify the code without using conditional operators in such cases:
TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With