Sunday, May 5, 2024
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 9916  / 2 Years ago, sun, july 31, 2022, 6:38:38

I've been told in php it's preferred to avoid the use of the exit command as much as possible.



Is the same true for bash?



For example is the following



#!/bin/bash
if [ -z $1 ]; then
echo You need to enter the directory you want to backup
else
sourceFile=$1
targetFile=/home/me/Desktop/myBackups/files_$(date +%Y_%m_%d_%s)
tar cvf $targetFile $sourceFile
fi


Preferred to this?



#!/bin/bash
if [ -z $1 ]; then
echo You need to enter the directory you want to backup
exit
fi
sourceFile=$1
targetFile=/home/me/Desktop/myBackups/files_$(date +%Y_%m_%d_%s)
tar cvf $targetFile $sourceFile

More From » command-line

 Answers
4

Quoting 'Code Complete'




Use [exit] when it enhances readability In certain routines, once
you know the answer, you want to [exit] to the calling routine
immediately. If the routine is defined in such a way that it doesn’t
require any further cleanup once it detects an error, not [exiting]
immediately means that you have to write more code.




So normally one exit is preferred (people looking at your code don't have to find the correct exit statement), however with error checking (especially at the start of a program/routine having multiple exit statements is clearer.



Your example is borderline, however I would say that the second is preferred so that maintenance to your program/script can leave it tidy.



Your program currently is (in psudocode)



if error condition 1
// Show error message 1
else
// Do stuff
fi


or



if error condition 1
// Show error message 1
// exit
fi

// Do stuff





Once your program has grown, you realise some more ways that the program can fail. Your program now becomes



if error condition 1
// Show error message 1
else
if error condition 2
// Show error message 2
else
if error condition 3
// Show error message 3
else
// Do stuff
fi
fi
fi


or maybe



if error condition 1
// Show error message 1
else if error condition 2
// Show error message 2
else if error condition 3
// Show error message 3
else
// Do stuff
fi


versus



if error condition 1
// Show error message 1
// exit
else if error condition 2
// Show error message 2
// exit
else if error condition 3
// Show error message 3
// exit
fi

// Do stuff


In my mind, the last one is the clearest in being able to spot which is the error cases and which is the main flow of the program. Now add returning different values (eg. 0 on success, 1 on error 1, 2 on error 2, etc.) and the difference will become more pronounced.


[#41637] Sunday, July 31, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
assionortly

Total Points: 423
Total Questions: 121
Total Answers: 115

Location: Chad
Member since Wed, Sep 30, 2020
4 Years ago
;