Last active
June 23, 2024 19:34
-
-
Save luciomartinez/c322327605d40f86ee0c to your computer and use it in GitHub Desktop.
Add or Remove trailing slash in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Add trailing slash if needed | |
STR="/i/am/a/path" | |
length=${#STR} | |
last_char=${STR:length-1:1} | |
[[ $last_char != "/" ]] && STR="$STR/"; : | |
echo "$STR" # => /i/am/a/path/ | |
### Remove trailing slash if given | |
STR="/i/am/a/path/" | |
length=${#STR} | |
last_char=${STR:length-1:1} | |
[[ $last_char == "/" ]] && STR=${STR:0:length-1}; : | |
echo "$STR" # => /i/am/a/path |
another way to do it:
[[ ! $(echo ${STR} | rev | cut -d '/' -f 1 | rev) == "" ]] && STR=${STR}/
[[ $(echo ${STR} | rev | cut -d '/' -f 1 | rev) == "" ]] && STR=$(echo $STR | sed 's/.$//')
it is not better then you said, jsut another way
add slash
STR="${STR%/}/"
remove slash
STR="${STR%/}"
add slash
STR="${STR%/}/"
remove slash
STR="${STR%/}"
Nicely done!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With Bash 4.2 this can be condensed into one-liners:
[[ "${STR}" != */ ]] && STR="${STR}/"
[[ "${STR}" == */ ]] && STR="${STR: : -1}"