You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下如何将systemctl获取的运行时间解析为秒数

刚好遇到过类似的需求,给你一个实用的bash解决方案,能完美处理你列出的所有7种时长格式,把systemctl获取的Cassandra运行时长转换成总秒数:

完整脚本实现

# 定义转换函数:将时长字符串转为总秒数
convert_to_seconds() {
    local total_seconds=0
    # 遍历输入的每个时间片段
    for segment in $1; do
        # 提取数字部分(去掉末尾的单位字符)
        local num=${segment%[a-z]*}
        # 提取单位部分(去掉开头的数字)
        local unit=${segment#[0-9]*}
        
        # 根据单位换算成秒并累加
        case "$unit" in
            day|days)
                total_seconds=$((total_seconds + num * 86400))
                ;;
            h|hr|hrs)
                total_seconds=$((total_seconds + num * 3600))
                ;;
            min|mins)
                total_seconds=$((total_seconds + num * 60))
                ;;
            sec|secs)
                total_seconds=$((total_seconds + num))
                ;;
        esac
    done
    echo "$total_seconds"
}

# 从systemctl获取Cassandra的运行时长并存储到变量A
A=$(systemctl status cassandra | awk '/(Active: active)/{print $9, $10, $11}')

# 调用函数转换并输出结果
echo "Cassandra运行总秒数:$(convert_to_seconds "$A")"

代码细节解释

  • 变量A的获取:直接复用了你原有的命令逻辑,精准提取systemctl输出中的运行时长片段。
  • 转换函数的核心逻辑:
    • 自动拆分时长字符串为单个片段(比如3 day 18h会拆成3、day、18、h)
    • 用bash参数扩展分离数字与单位:${segment%[a-z]*}去掉末尾字母得到纯数字,${segment#[0-9]*}去掉开头数字得到单位
    • 通过case语句匹配不同单位,按换算规则累加秒数:1天=86400秒,1小时=3600秒,1分钟=60秒,秒直接计入总数
  • 兼容性处理:加入了days、hrs、mins、secs等复数/完整单位写法,避免因systemctl输出的微小差异导致解析失败。

测试示例

针对你列出的7种格式,这个脚本都能正确转换:

  • 3 day 18h → 3*86400 + 18*3600 = 302400秒
  • 3 day → 3*86400 = 259200秒
  • 3h 15min → 3*3600 +15*60 = 11700秒
  • 3h → 3*3600 = 10800秒
  • 15min 10sec → 15*60 +10 = 910秒
  • 15min → 15*60 = 900秒
  • 10sec → 10秒

内容的提问来源于stack exchange,提问作者Parul Chourasia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:19:54