What are other bash operators?

089

In addition to && (AND) and || (OR), there are several other operators in bash that you can use for various purposes. Here are some common ones:

1. Logical Operators

  • ! : Logical NOT operator. It negates the exit status of a command.
    ! command  # Executes the command and returns true if it fails.

2. Comparison Operators

  • -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 [ "$a" -eq "$b" ]; then
        echo "a is equal to b"
    fi

3. File Test Operators

  • -e : Checks if a file exists.
  • -f : Checks if it is a regular file.
  • -d : Checks if it is a directory.
  • -s : Checks if a file is not empty.
  • -r : Checks if a file is readable.
  • -w : Checks if a file is writable.
  • -x : Checks if a file is executable.
    if [ -f "file.txt" ]; then
        echo "file.txt exists and is a regular file."
    fi

4. Arithmetic Operators

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • % : Modulus
    result=$((a + b))

5. String Operators

  • = : Checks if two strings are equal.
  • != : Checks if two strings are not equal.
  • -z : Checks if a string is empty.
  • -n : Checks if a string is not empty.
    if [ -z "$string" ]; then
        echo "String is empty."
    fi

6. Redirection Operators

  • > : Redirects output to a file (overwrites).
  • >> : Redirects output to a file (appends).
  • < : Redirects input from a file.
  • 2> : Redirects standard error to a file.
    command > output.txt  # Redirects output to output.txt
    command 2> error.txt  # Redirects errors to error.txt

These operators can be combined in various ways to create complex scripts and command sequences in bash.

0 Comments

no data
Be the first to share your comment!