I have a string
VAR_A="127.0.0.1:12345"
I want to split it into HOSTNAME
and PORT
, with the delimiter :
.
Per this post, I'm using this syntax to split the original VAR_A
string:
HOSTNAME=${VAR_A%%:*}
PORT=${VAR_A#*:}
And it works if VAR_A
if of the form xxxx:xxxx
.
But I'd like to have the following result according to the value passed to VAR_A
:
- If
VAR_A
doesn't contain the char:
, e.g.VAR_A=127.0.0.1
, thenHOSTNAME
is assigned with127.0.0.1
, and assign empty string toPORT
- If
VAR_A
contains the char:
but nothing is after that:
, e.g.VAR_A=127.0.0.1:
, then same,HOSTNAME
is assigned with127.0.0.1
, and assign empty string toPORT
- If
VAR_A
contains the char:
but nothing before that:
, e.g.VAR_A=:12345
, then assign empty string toHOSTNAME
, and12345
toPORT
.
With current codes, if VAR_A=127.0.0.1
, I got both HOSTNAME=127.0.0.1
and PORT=127.0.0.1
, which is not desired.
If doable, I'd prefer a syntax similar to the one I provided -- the more succint/elegant the better.