Skip to content

Instantly share code, notes, and snippets.

@luciomartinez
Last active June 1, 2023 08:49
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save luciomartinez/c322327605d40f86ee0c to your computer and use it in GitHub Desktop.
Save luciomartinez/c322327605d40f86ee0c to your computer and use it in GitHub Desktop.
Add or Remove trailing slash in bash
### 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
@kopardev
Copy link

add slash

STR="${STR%/}/"

remove slash

STR="${STR%/}"

@iforwms
Copy link

iforwms commented Nov 2, 2021

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