caffreyd
caffreyd

Reputation: 1203

How to Capture Values from an Argument in HH:MM Format for a Shell Script

I'd like to build a Linux script with an argument in the format HH:MM.

An example invocation:

./my_script.sh 08:30

Within the script, I'd like to assign the hours and minutes to 2 vars, HRS and MINS.

So, for my example invocation HRS would be assigned the value 8, and MINS would be assigned the value 30.

I don't want an invocation format like:

./my_script.sh -hrs 08 -mins 30

How should I parse my input argument to get hours and minutes?

Upvotes: 1

Views: 43

Answers (1)

trs
trs

Reputation: 349

Very similar to this answer here: https://stackoverflow.com/a/918931/3421151

Using IFS with read works well since you can delimit the first argument by : which gives you an array of the hours and mins.

IFS=':' read -ra TIME <<< "$1"
HRS="${TIME[0]}"
MINS="${TIME[1]}"

echo "HRS: $HRS"
echo "MINS: $MINS"

Upvotes: 1

Related Questions