What is the easiest way to remove trailing slash from each parameter?

What is the easiest way to remove the trailing slash from each parameter in the $ @ array so that rsync copies directories by name?

 rsync -a --exclude='*~' "$@" "$dir" 



The name has been changed to clarify. To understand the comments and response to a few trailing slashes, review the change history.

+48
bash shell arguments rsync stripslashes
Jan 26 '12 at 13:24
source share
6 answers

You can use the extension ${parameter%word} , which is described in detail here . Here is a simple script test that demonstrates the behavior:

 #!/bin/bash # Call this as: # ./test.sh one/ two/ three/ # # Output: # one two three echo ${@%/} 
+88
Jan 26 2018-12-12T00:
source share

This works for me: ${VAR%%+(/)}

As described here http://wiki.bash-hackers.org/syntax/pattern

You may need to set the extglob shell option. I don’t see it being turned on for me, but it still works

+11
Jan 08 '15 at 17:55
source share

The accepted answer trims ONE end of the slash.

One way to trim multiple trailing slashes is as follows:

 VALUE=/looks/like/a/path/// TRIMMED=$(echo $VALUE | sed 's:/*$::') echo $VALUE $TRIMMED 

What outputs:

 /looks/like/a/path/// /looks/like/a/path 
+10
Sep 29 '15 at 13:45
source share

In zsh, you can use the modifier :a .

 export DIRECTORY='/some//path/name//' echo "${DIRECTORY:a}" => /some/path/name 

This acts like a realpath , but does not fail with the absence of files / directories as an argument.

+2
Oct 28 '15 at 1:03
source share

realpath resolves the given path. Among other things, it also removes trailing slashes. Use -s to prevent the following symlinks

 DIR=/tmp/a/// echo $(realpath -s $DIR) # output: /tmp/a 
+2
Jul 07 '17 at 14:36
source share

FYI, I added these two functions to my .bash_profile based on the answers found on SO. As Chris Johnson said, all answers using ${x%/} remove only one slash, these functions will do what they say, hope this is useful.

 rem_trailing_slash() { echo $1 | sed 's/\/*$//g' } force_trailing_slash() { echo $(rem_trailing_slash $1)/ } 
+1
Aug 16 '16 at 11:04 on
source share



All Articles