Ensuring a single colon at start of string

58 views Asked by At

I am using getopts to parse options. I want to ensure that the optstring has only a single colon at the start, and if this does not exist I want to introduce it.

Here is an example of the initialisation of optstring

  local optstring="sn:z:" 
2

There are 2 answers

6
Charles Duffy On BEST ANSWER
optstring=:${optstring#:}

First we unconditionally add a colon, then we use a parameter expansion to expand our string with any preexisting colon removed.

1
pjh On

This POSIX-compatible code (tested with Bash and Dash) handles arbitrary numbers of colons at the start of the string:

optstring=:${optstring#${optstring%%[!:]*}}
  • ${optstring%%[!:]*} expands to the (possibly empty) string of colons at the start of $optstring. It does this by removing the first non-colon character ([!:]) and everything that follows it.
  • ${optstring#${optstring%%[!:]*}} expands to $optstring with all the colons at the start removed.

The transformation can be done in two steps to (possibly) make it more readable:

colons=${optstring%%[!:]*}
optstring=:${optstring#$colons}

Another (also POSIX-compatible) approach is to use a loop to remove leading colons:

while [ "${optstring#:}" != "$optstring" ]; do
    optstring=${optstring#:}
done
optstring=:$optstring