6 Bash Conditional Expression Examples ( -e, -eq, -z, !=, [, [[ ..)

来源:互联网 发布:mac怎么使用搜狗 编辑:程序博客网 时间:2024/05/20 22:30

Bash expression is the combination of operators, features, or values used to form a bash conditional statement. Conditional expression could be binary or unary expression which involves numeric, string or any commands whose return status is zero when success.

There are several conditional expressions that could be used to test with the files. Following are few conditional expressions that are helpful.

  • [ -e filepath ] Returns true if file exists.
  • [ -x filepath ] Returns true if file exists and executable.
  • [ -S filepath ] Returns true if file exists and its a socket file.
  • [ expr1 -a expr2 ] Returns true if both the expression is true.
  • [ expr1 -o expr2 ] Returns true if either of the expression1 or 2 is true.

For more conditional expression to check the files, strings and numerics please refer the bash man page.

Bash Example 1. Check File Existence

The following Bash shell script code-snippet gets the filename with its absolute path, and checks if the file exists or not and it throws the appropriate information.

$ cat exist.sh#! /bin/bashfile=$1if [ -e $file ]thenecho -e "File $file exists"elseecho -e "File $file doesnt exists"fi$ ./exist.sh /usr/bin/boot.iniFile /usr/bin/boot.ini exists

Refer to our previous article to understand the various bash if statement types.

Bash Example 2. Compare Numbers

The below script reads two integer numbers from user, and checks if both the numbers are equal or greater or lesser than each other.

$ cat numbers.sh#!/bin/bashecho "Please enter first number"read firstecho "Please enter second number"read secondif [ $first -eq 0 ] && [ $second -eq 0 ]thenecho "Num1 and Num2 are zero"elif [ $first -eq $second ]thenecho "Both Values are equal"elif [ $first -gt $second ]thenecho "$first is greater than $second"elseecho "$first is lesser than $second"fi$ ./numbers.shPlease enter first number1Please enter second number1Both Values are equal$ ./numbers.shPlease enter first number3Please enter second number123 is lesser than 12

If you are new to bash scripting, refer to our Bash Introduction tutorial.

Bash Example 3. Basic Arithmetic Calculator

This examples reads input, which is a type of arithmetic operation wants to perform on bash variables (inp1 and inp2). The arithmetic operation could be addition, subtraction or multiplication..

$ cat calculator.sh#!/bin/bashinp1=12inp2=11echo "1. Addition"echo "2. Subtraction"echo "3. Multiplication"echo -n "Please choose a word [1,2 or 3]? "read operif [ $oper -eq 1 ]thenecho "Addition Result " $(($inp1 + $inp2))elseif [ $oper -eq 2 ]thenecho "Subtraction Result " $(($inp1 - $inp2))elseif [ $oper -eq 3 ]thenecho "Multiplication Result " $(($inp1 * $inp2))elseecho "Invalid input"fififi$ ./calculator.sh1. Addition2. Subtraction3. MultiplicationPlease choose a word [1,2 or 3]? 4Invalid input

Knowing how to use the bash special parameters ( $*, $@, $#, $$, $!, $?, $-, $_ ) will make your scripting life easy.

Bash Example 4. Read and Ping IP address

The following script is used to read the IP address and check whether the IP address is reachable, and prints the appropriate message.

$ cat ipaddr.sh#!/bin/bashecho "Enter the Ipaddress"read ipif [ ! -z $ip ]thenping -c 1 $ipif [ $? -eq 0 ] ; thenecho "Machine is giving ping response"elseecho "Machine is not pinging"fielseecho "IP Address is empty"fi$ ./ipaddr.shEnter the Ipaddress10.176.191.106Pinging 10.176.191.106 with 32 bytes of data:Reply from 10.176.191.106: bytes=32 time<1ms TTL=128Ping statistics for 10.176.191.106:    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),Approximate round trip times in milli-seconds:    Minimum = 0ms, Maximum = 0ms, Average = 0msMachine is giving ping response

In this example, -z returns true if ipaddress is zero length, When the condition is preceded by ! (negate) operator, if expression is false, it enters into if part and executes. So when the IP address is not null, it enters and checks whether the ip address is reachable.

Bash Example 5. Installer Script

Installer script of most of the packages will not allow to execute those as a root user. Script checks the user who is executing and throws the error.

The following script, allows you to execute the oracle installer script only if the user who is executing is non root.

$ cat preinstaller.sh#!/bin/bashif [ `whoami` != 'root' ]; thenecho "Executing the installer script"./home/oracle/databases/runInstaller.shelseecho "Root is not allowed to execute the installer script"fiExecuting the script as a root user,# ./preinstaller.shRoot is not allowed to execute the installer script

In this example the output of the command whoami is compared with the word “root”. For string comparison ==, !=, < and should be used and for numeric comparison eq, ne,lt and gt should be used.

Bash Example 6. Enhanced brackets

In all the above examples, we used only single brackets to enclose the conditional expression, but bash allows double brackets which serves as an enhanced version of the single-bracket syntax.

$ cat enhanced.sh#!/bin/bashecho "Enter the string"read strif [[ $str == *condition* ]]thenecho "String "$str has the word \"condition\"fi$ ./enhanced.shEnter the stringconditionalstatementString conditionalstatement has the word "condition"
  • [ is a synonym for test command. Even if it is built in to the shell it creates a new process.
  • [[ is a new improved version of it, which is a keyword, not a program.
  • [[ is understood by Korn and Bash.
  • In the above example, if the variable $str contains the phrase “condition” anywhere, the condition is true.
  • This is the shell globbing feature, which will be supported only when you use [[ (double brackets) and therefore many arguments need not be quoted.
原创粉丝点击