11

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?

  • Require that the user enter a trailing / (forward slash)
  • Require that a user doesn't enter a trailing / (forward slash)
Stevoisiak
  • 1,354

5 Answers5

28

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.

ChrisF
  • 38,948
  • 11
  • 127
  • 168
10

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.

cat /etc/hosts

is the same like

cat /////etc//////////hosts

So your script could look like that:

echo -n "enter path: "
read path
if [ -f $path/myfile ]
then
  echo "found myfile!"
else
  echo "nope"
fi

and you don't have to worry whether or not the user enters a trailing / in the path.

user281377
  • 28,434
7

The late Jon Postel had some great advice in section 3.2 of RFC 760 that applies here:

In general, an implementation should be conservative in its sending behavior, and liberal in its receiving behavior. That is, it should be careful to send well-formed datagrams, but should accept any datagram that it can interpret (e.g., not object to technical errors where the meaning is still clear).

Blrfl
  • 20,525
3

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:

a="/home"
b="stefan"

dir=$a/$b
0

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.

oberlies
  • 466
  • 4
  • 16