BASH Programming

What does “-ne” mean in Bash

Bash is a popular Unix shell and command language used in various operating systems, including Linux and macOS.The ability to modify the behaviour of scripts using command-line arguments is one of Bash’s key features. One such argument is the “-ne” option, which has a specific meaning in Bash.

What does “-ne” mean in Bash?

The “-ne” option is a conditional expression used in Bash scripts to test if two values are not equal.Making decisions based on the outcome of the comparison is a typical practise in bash if statements. When combined the test command is used for such purpose, it returns true if the two numbers are not equal and false if they are.

Example 1

Let’s see an example that checks the input given by the user using the -ne option, below is the code for it:

#!/bin/bash
read -p "Enter a number: " num
if [ $num -ne 0 ]
then
    echo "The number you entered is not zero."
else
    echo "The number you entered is zero."
fi

In this example, the script prompts the user to enter a number and then uses the “-ne” option to test if the number is not equal to zero.The script displays a message indicating that the number is not zero if it is not zero, and a message indicating that the number is zero otherwise.

Example 2

Here is another example that compares the value using the -ne operator, below is the code for it:

#!/bin/bash

num=15

if [ $num -ne 10 ]; then
  echo "The variable num is not equal to 10."
fi

The script sets the value of $num to 15, and then uses the -ne operator to check if it is not equal to 10. Since 15 is not equal to 10, the script will output the message “The variable num is not equal to 10:

Conclusion

The “-ne” option in Bash scripts used for testing two values are not equal. It is commonly used in if statements to make decisions based on the result of the comparison. The two examples provided demonstrate how “-ne” can be used in Bash scripts to make decisions based on user input and variable values.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.