0

I'm trying to split a string in ash shell using only the tools provided in BusyBox.

The string is of the format host-name:port,host-name2:port2 but I only care about the first hostname and port, both of which I'd like access to as variables.

I've tried a few options I found on here but most pertain to bash and the equivalent commands/functionality doesn't seem to exist in ash shell.

Any ideas?

  • echo ${string%,*} – Ipor Sircer Aug 21 '18 at 12:42
0

An agnostic (for many shells) solution that works correctly with spaces, newlines and empty fields is:

#!/bin/bash
in='One-XX-X-17.0.0'

a=$in; div='-'; set --
    while
    b=${a#*"$div"}
    set -- "$@" "${a%%"$div"*}"
    [ "$a" != "$b" ]
    do
    a=$b
    done
printf 'Element: %s\n' "$@"

#split 17.0.0 into NUM
a=$4; div='.'; set --
    while
    b=${a#*"$div"}
    set -- "$@" "${a%%"$div"*}"
    [ "$a" != "$b" ]
    do
    a=$b
    done
printf 'Num: %s\n' "$@"

Which will print:

$ ./script
Element: One
Element: XX
Element: X
Element: 17.0.0
Num: 17
Num: 0
Num: 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.