Logical Not !

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Logical ORHomeConditional expression →

Logical not (!) is boolean operator, which is used to test whether expression is true or not. For example, if file not exists, then display an error on screen.

Syntax

The test command syntax is as follows:

! expression

OR

[ ! expression ]

OR

if test ! condition
then
     command1
     command2
fi
if [ ! condition ]
then
     command1
     command2
fi

Where,

  • True if expression is false.

Examples

Try the following example:

test ! -f /etc/resolv.conf && echo "File /etc/resolv.conf not found."

OR

test ! -f /etc/resolv.conf && echo "File /etc/resolv.conf not found." || echo "File /etc/resolv.conf found."

Create a directory /backup, if doesn't exits:

[ ! -d /backup ] && mkdir /backup

Die (exit) if $HOME/.config file not found:

[ ! -f $HOME/.config ] && { echo "Error: $HOME/.config file not found."; exit 1; }

Die (exit) if directory /usr/bin not found

[ ! -d /usr/bin ] && exit

Here is a sample script that use logical not ! to make backup directories on fly:

#!/bin/bash
# A sample shell script to backup MySQL database
 
# Get todays date
NOW=$(date +"%d-%m-%Y")
 
# Location to store mysql backup
BAK="/nas10/.mysql-database"
 
# MySQL Server Login Information
MUSER="root"			#### mysql user name ###
MPASS="YOUR-PASSWORD-HERE"	#### mysql password  ###
MHOST="127.0.0.1"		#### mysql host name ###
 
# Full path to common utilities
MYSQL="/usr/bin/mysql"
MYSQLDUMP="/usr/bin/mysqldump"
GZIP="/bin/gzip"
 
# If backup directory does not exits create it using logical not
if [ ! -d "$BAK" ]
then
  mkdir -p "$BAK"
fi
 
# Get all mysql databases names
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
 
# Start backup
echo -n "Dumping..."
 
# Use the for loop
for db in $DBS
do
 FILE="$BAK/mysql-$db.$NOW-$(date +"%T").gz"
  $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE
 echo -n "."
done
echo -n  "...Done"
echo ""
  • Please note that the bash shell pipes also support ! operator. It "reverses" the exit code of a command.
← Logical ORHomeConditional expression →