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

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

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.


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.