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 ‘/’.

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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