Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - How to strip the first and last slash in a string if present?

Tags:

bash

What is the most effective way to get:

'a/b/c'

out of input string that can be any of the following:

'/a/b/c/'
'a/b/c/'
'/a/b/c'
'a/b/c'

in a bash script?

like image 448
Edward Avatar asked Apr 14 '18 05:04

Edward


1 Answers

I don't know about "most effective", but if that string is stored in the variable a (that is $a expands to the string) you can do:

b=${a#/} # Remove possible leading /
c=${b%/} # Remove possible trailing /

to put the desired string in the variable c. This doesn't work if your input string contains single quotes as you have written in the question, but I suspect you did not intend to indicate that such quotes are in the string.

like image 85
William Pursell Avatar answered Oct 13 '22 00:10

William Pursell