wooden wooden - 7 months ago 19
Bash Question

How to make two variables from one positional parameter?

I need to add two numbers to a positional argument $1 with a dash between them i.e. "15-20". It is an interval from 15 to 20 and it has to be a one positional parameter. I did this:

a=$(echo "$1" | sed 's/-/ /g')
echo $a

It prints:
15 20
I will need this in the future as an interval so I have to take each of these numbers as a seperate variables. Instead of a = 15 20, it should be a = 15 and b = 20. How can I achieve this?


Using bash you can use process substitution:

read a b < <(echo "$1" | sed 's/-/ /g')

# and check values
declare -p a b
declare -- a="15"
declare -- b="20"

As the helpful comment from @chepner below, you don't even need sed. You can use read both variables using a custom IFS:

IFS=- read a b <<< "$1"