How to remove trailing / in path in Bash?

I am writing a Bash script accepting input of a path from the user. I want to make the path have no trailing ‘/’, such as ‘/path/to/dir’ instead of ‘/path/to/dir/’.

However, as the input is from the user, the input could be ‘/path/to/dir’. My script is intended to handle this.

The question is: how to remove the trailing ‘/’ if the input indeed has it? When the input has not trailing ‘/’, it should be fine.

You may do in a straight forward way like check whether the last character is ‘/’ and the path is a to a directory and remove that ‘/’ from the string.

But here I provide another much easier method:

`dirname $path`/`basename $path`

will consistently gives the same path without the trailing ‘/’ no matter whether the path is a directory or a file without or without the trailing ‘/’.

Similar Posts

  • OCaml Learning Materials

    OCaml is an interesting functional language. There are lots learning materials on the Internet. I compile a list of resources for OCaml learning and reference. Recommended OCaml learning and reference material Online book of Real World OCaml by Yaron Minsky, Anil Madhavapeddy, Jason Hickey. A very good tutorial by Jason Hickey: http://www.cs.caltech.edu/courses/cs134/cs134b/book.pdf. The OCaml system…

  • How to restore a Gnome 3 session?

    How to restore a Gnome 3 session? Which means: opening all the programs running last time when I log out in Gnome 3. If your purpose is to automatically start programs after logging in Gnome, another possible method is using the autostart script: https://www.systutorials.com/qa/119/how-to-write-a-autostart-script-for-gnome Run gnome-session-properties. In the “Options” tab, select “Automatically remember running applications…

  • How to get logs of a specific time range on Linux?

    The logs I am processing is Hadoop log (log4j). It is in format like: 2014-09-20 21:55:11,855 INFO org.apache.hadoop.nfs.nfs3.IdUserGroup: Updated user map size: 36 2014-09-20 21:55:11,863 INFO org.apache.hadoop.nfs.nfs3.IdUserGroup: Updated group map size: 55 2014-09-20 22:10:11,907 INFO org.apache.hadoop.nfs.nfs3.IdUserGroup: Update cache now 2014-09-20 22:10:11,907 INFO org.apache.hadoop.nfs.nfs3.IdUserGroup: Not doing static UID/GID mapping because ‘/etc/nfs.map’ does not exist. Now, I…

Leave a Reply

Your email address will not be published. Required fields are marked *