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:
| |||
|
Requiring that the directory must not have a trailing slash would be extremely annoying for interactive use on the console: auto-completion with TAB automatically adds a trailing slash for directories. So you certainly need to allow that directories are specified with trailing slash. | |||
|
rsync
behaves differently in a very important way depending on the presence of trailing/
, and so in some cases you'd want to normalise for consistency, and in others you'd want to pass through cleanly to implement what the user said (if they knew they were talking torsync
). – sh1 Jul 3 at 13:10