I want to ask the user of my bash script to pass a directory path as argument. Which one of the following is a good programming practice - to require that the user enter a trailing / (forward slash) or to require that a user doesn't enter a trailing / (forward slash)?
Best practice is to assume neither. If you have access to path builder utilities/classes use those, if not write your code to accept either format and act accordingly. Nothing's more annoying for the user than having to remember whether to add a trailing slash or not. |
|||||||||
|
Since bash ignores multiple slashes, you can safely assume that the user didn't enter a trailing slash in the path and add a slash yourself.
is the same like
So your script could look like that:
and you don't have to worry whether or not the user enters a trailing / in the path. |
|||||||
|
The late Jon Postel had some great advice in section 3.2 of RFC 760 that applies here:
|
|||
|
Conceptually, the slash is not part of the name. The slash is only a delimiter between names. My home-dir is /home/stefan and not /home/stefan/. If you don't expect a trailing slash, you will not fail if there is one, as ammoQ already noted. But you can easily glue together names and vars, because you don't have to quote the slash:
|
|||
|