» IT tipps and howto's

Shell scripting: if test [] examples

Last Update: 12.11.2009

Here you may find several examples of test constructs.

Important operators (for integers) to keep in mind:
-eq equal to
-ne not equal to
-lt less than
-le less than or equal to
-gt greater than
-ge greater than or equal to

If you test the existance of files:
-s file exists and is not empty
-f file exists and is not a directory
-d directory exists
-x file is executable
-w file is writable
-r file is readable

# Compares the values of two variables
if [ ${value1} = ${value2} ]
then echo "Both variables have the same value"
else echo "The variables values differ!"
fi

# Checks if a variable is NULL or not (#1 with -n and quotes)
if [ -n "${var}" ]
then echo "The variable is not empty (not null)"
else echo "The variable is NULL"
fi

# Checks if a variable is NULL or not (#2)
if [ ${var} ]
then echo "The variable is not empty (not null)"
else echo "The variable is NULL"
fi

# Checks if a variable is bigger than a number (INTEGER)
if [ ${var} > 2 ]
then echo "The variable is bigger than two"
else echo "The variable is smaller than two"
fi

# The previous test doesnt work if the integer is 0 so do this:
if [ ${var} -gt 0 ]
then echo "The variable is bigger than zero"
else echo "The variable is smaller than zero"
fi

# Combination of two tests (note the echo 'at least')
if [ ${var1} > 2 ] || [ ${var2} > 2 ]
then echo "At least one of both variables is bigger than two"
else echo "No variable is bigger than two"
fi

# Combination of two tests (note the echo 'both')
if [ ${var1} > 5 ] && [ ${var2} > 5 ]
then echo "Both variables are bigger than five"
else echo "Not both variables are bigger than five"
fi

 

RSS feed

Blog Tags:

  AWS   Android   Ansible   Apache   Apple   Atlassian   BSD   Backup   Bash   Bluecoat   CMS   Chef   Cloud   Coding   Consul   Containers   CouchDB   DB   DNS   Database   Databases   Docker   ELK   Elasticsearch   Filebeat   FreeBSD   Galera   Git   GlusterFS   Grafana   Graphics   HAProxy   HTML   Hacks   Hardware   Icinga   Influx   Internet   Java   KVM   Kibana   Kodi   Kubernetes   LVM   LXC   Linux   Logstash   Mac   Macintosh   Mail   MariaDB   Minio   MongoDB   Monitoring   Multimedia   MySQL   NFS   Nagios   Network   Nginx   OSSEC   OTRS   Office   OpenSearch   PGSQL   PHP   Perl   Personal   PostgreSQL   Postgres   PowerDNS   Proxmox   Proxy   Python   Rancher   Rant   Redis   Roundcube   SSL   Samba   Seafile   Security   Shell   SmartOS   Solaris   Surveillance   Systemd   TLS   Tomcat   Ubuntu   Unix   VMWare   VMware   Varnish   Virtualization   Windows   Wireless   Wordpress   Wyse   ZFS   Zoneminder