1

I am following an instruction and confuse with the usage of exit

    FILE=~/.bashrc
    if [ -e "$FILE" ] ; then
        if [ -f "$FILE" ]; then
            echo "$FILE is a regular file."
        fi
        if [ -d "$FILE" ]; then
            echo "$FILE is a directory."
        fi
        if [ -r "$FILE" ] ; then
            echo "$FILE is readable."
        fi
        if [ -w "$FILE" ] ; then
            echo "$FILE is writabe."
        fi
        if [ -x "$FILE" ]; then
            echo '$FILE is executable/searchable.'
        fi
        else
            echo '$FILE does not exist'
            exit 1
        fi
    exit

Run and come by

    $ bash test_file.sh
    /Users/me/.bashrc is a regular file.
    /Users/me/.bashrc is readable.
    /Users/me/.bashrc is writabe.

If comment out commands of exit, the output stay unchanged.

What's its function? Could I leave out the exits when familiar with the language.

2

The exit command not only exits a script, but also sets an exit code, which by convention is zero for a successful exit, and some other integer for an error, so in your script, its purpose is to indicate to the caller (either another script / program, or a user) that the program exited with an error. In bash and similar shells, one can view or interrogate the exit code by examining shell variable $?.

Also, BTW, you have an indentation problem. The else clause should be out-dented to the same level as the initial if statement...

  • so, it's not a compulsive requirement? – Algebra Apr 3 '18 at 2:38
  • @Tool - Using exit commands with exit codes is not required, but it is good practice, so it's worthwhile to get into the habit, and to assign unique and consistent exit codes for uniqe error conditions. See here for a list of the error codes used by linux itself: unix.stackexchange.com/a/326811/153769 , but do be aware that other operating systems may have other standards. – user1404316 Apr 3 '18 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.