user1950349 user1950349 - 20 days ago 4x
Bash Question

split a string on a - delimiter in bash?

How do I split a string basis on a delimiter in Bash?

I have string stored in a variable as shown below:


Now I would like to split above string on
delimiter and store two numbers in two different variables.


If NUMBER1 and NUMBER2 is an empty string and not a number then exit out of the script with non zero status code.

IFS=- read -r number1 number2 _ <<<"$DATA"
[[ $number1 && $number2 ]] || { echo "Initial columns not read" >&2; exit 1; }
[[ $number1$number2 = *[![:digit:]]* ]] && { echo "Values are not numeric" >&2; exit 1; }

echo "Number 1 is $number1"
echo "Number 2 is $number2"

Setting IFS to your delimiter on the same line as the read command (with no separator such as ; between) scopes it to that single read operation, so it won't modify the shell's behavior elsewhere in the script.

Note the _ as an extra argument to read -- the rest of the line is stored there, preventing it from being appended to number2.