跨平台时间读取问题:Linux脚本在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-fto 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:
Other commonone_hour_ago=$(date -v -1H +"%Y-%m-%d %H:%M:%S")-vmodifiers:-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, useTZ='Asia/Shanghai' dateinstead. - Other Linux-Specific Commands: If your script uses tools like
readlink -f(not available in BSDreadlink), you can install the GNU version via Homebrew (brew install coreutils) and usegreadlinkinstead.
If you share a snippet of your original script, I can help tailor the fix even more!
内容的提问来源于stack exchange,提问作者djl

