What is the : division by 0 (error token is "etc/shadow ") error?

Viewed 421

I am a beginner at Bash scripting and I am getting an error saying this when I run my code:

main.sh: line 7: ((: -w /etc/shadow : division by 0 (error token is "etc/shadow ")

The following is the code I wrote in main.sh:

#!/usr/bin/env bash

if [ -e /etc/shadow ]
then
    echo "Shadow passwords are enabled."

    if (( -w /etc/shadow ))
    then
        echo "You have permissions to edit /etc/shadow"
    else
        echo "You do NOT have permissions to edit /etc/shadow"
    fi
else
    echo "Shadow passwords are not enabled."
fi

The result after running the code also gave:

Shadow passwords are enabled.

You do NOT have permissions to edit /etc/shadow

This was given before the error message. Does anyone have any suggestions for how to fix this problem and what the error message means? Thanks!

1 Answers

You should use [[ ... ]] (preferred, bash-only) or [ ... ] (can cause problems, POSIX compliant) instead of (( ... )): they are adequate for comparing text, while (( ... )) is an arithmetic context and only accepts mathematical operations. The error occurs because it tries to use the /s in the path for division.

That error counts as a false for the if, making you run the else block.

if [[ -w /etc/shadow ]]
then
# ...

A good reference for using if in bash is the Bash Beginner Guide.

Related