简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM