I'm trying to trim a possible /
from the start and end of a string in bash.
I can accomplish this via the following:
string="/this is my string/"
string=${string%/}
string=${string#/}
echo $string # "this is my string"
However, I would like to know if there's a way to join those two lines (2 + 3) to replace both at once. Is there a way to join the substitution, or is that the best I'm going to get?
Unfortunately there's no way to do that. However if you're sure that your string begins in / and ends in / you can trim it by ${P:M:N}
format:
string='/this is my string/'
string=${string:1:(-1)}
Adding a check could also help but it's still two statements:
[[ $string == /*/ ]] && string=${string:1:(-1)}
Note: Solution is only available starting Bash 4.2.