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

跨平台时间读取问题:Linux脚本在MacOS Sierra 10.12.6无法运行

Fixing Your Time-Tracking Script for macOS Sierra 10.12.6

Hey there! The main reason your script works on Linux but not macOS Sierra is almost certainly the date command—Linux uses the GNU version of date, while macOS ships with the BSD variant, and they have key syntax differences for date parsing, relative time, and timestamp conversion. Let's break down the most common fixes:

1. Convert Dates to Unix Timestamps

If your script relies on converting human-readable dates to Unix timestamps (for calculating durations), the syntax differs:

  • Linux (GNU date):
    timestamp=$(date -d "2024-05-20 14:30:00" +%s)
    
  • macOS (BSD date):
    You need to use -j (to avoid setting the system clock) and -f to define the input format:
    timestamp=$(date -j -f "%Y-%m-%d %H:%M:%S" "2024-05-20 14:30:00" +%s)
    

2. Relative Time Calculations

If your script uses relative time (e.g., "30 minutes ago" or "next day"), replace GNU's -d flag with BSD's -v option:

  • Linux:
    one_hour_ago=$(date -d "1 hour ago" +"%Y-%m-%d %H:%M:%S")
    
  • macOS:
    one_hour_ago=$(date -v -1H +"%Y-%m-%d %H:%M:%S")
    
    Other common -v modifiers: -30M (30 minutes ago), +1d (next day), -2w (2 weeks ago).

3. Cross-Platform Compatibility (Optional)

To make your script work on both Linux and macOS, add a check for the operating system using uname:

#!/bin/bash

# Get current timestamp and formatted time
if [[ "$(uname)" == "Darwin" ]]; then
    # macOS-specific logic
    start_time=$(date +"%Y-%m-%d %H:%M:%S")
    start_ts=$(date +%s)
else
    # Linux-specific logic
    start_time=$(date +"%Y-%m-%d %H:%M:%S")
    start_ts=$(date +%s)
fi

# Simulate work (replace with your actual task)
sleep 5

# Calculate end time and duration
if [[ "$(uname)" == "Darwin" ]]; then
    end_time=$(date +"%Y-%m-%d %H:%M:%S")
    end_ts=$(date +%s)
else
    end_time=$(date +"%Y-%m-%d %H:%M:%S")
    end_ts=$(date +%s)
fi

duration=$((end_ts - start_ts))
echo "Task completed in $duration seconds"
echo "Start: $start_time | End: $end_time"

4. Edge Cases to Check

  • Timezone Handling: On Linux, you might use date -d "TZ='Asia/Shanghai' now"—on macOS, use TZ='Asia/Shanghai' date instead.
  • Other Linux-Specific Commands: If your script uses tools like readlink -f (not available in BSD readlink), you can install the GNU version via Homebrew (brew install coreutils) and use greadlink instead.

If you share a snippet of your original script, I can help tailor the fix even more!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:17:38