简体   繁体   English

如何从 Shell 脚本的 HH:MM 格式的参数中捕获值

[英]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.我想构建一个带有 HH:MM 格式参数的 Linux 脚本。

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 .在脚本中,我想将小时和分钟分配给 2 个变量, HRSMINS

So, for my example invocation HRS would be assigned the value 8, and MINS would be assigned the value 30.因此,对于我的示例,调用HRS将被分配值 8,而MINS将被分配值 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与这里的答案非常相似: 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.IFSread一起使用效果很好,因为您可以通过:分隔第一个参数,它为您提供小时和分钟的数组。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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