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

Shell脚本报unexpected end of file与date无效选项错误如何解决

报错原因及解决办法

date: invalid option --v报错

原因:

  • macOS自带的是BSD版本date命令,支持-v参数做日期偏移调整
  • Linux、Windows下的WSL/Git Bash/Cygwin等环境默认搭载的是GNU版本date,不支持-v参数,因此会报无效选项错误

解决办法:将原日期计算逻辑替换为跨版本兼容的写法,替换set query_day=date -v -"$i"d +"%Y-%m-%d"``这一行为以下内容:

# 自动识别BSD/GNU date适配
if ( `date --version >/dev/null 2>&1` ) then
    # GNU date 适用Linux/Windows类Unix环境
    set query_day=`date -d "$i days ago" +"%Y-%m-%d"`
else
    # BSD date 适用macOS
    set query_day=`date -v -"$i"d +"%Y-%m-%d"`
endif

unexpected end of file报错

原因:

  • 该脚本为csh/tcsh语法,不是常用的bash语法,Windows环境默认没有安装csh/tcsh解释器,用bash直接运行会因为语法完全不匹配报错
  • 脚本从macOS迁移到Windows时,换行符被自动转换为Windows的CRLF格式,Unix系shell无法识别行尾的CR字符,解析逻辑错乱后抛出文件意外结束错误

解决办法:

  • 安装对应解释器:如果使用WSL环境,先执行sudo apt install tcsh安装tcsh,运行时用tcsh 你的脚本名.csh启动,不要用bash直接运行
  • 转换换行符:用文本编辑器打开脚本,另存为时将换行符设置为「LF」,或者用dos2unix工具执行dos2unix 你的脚本名.csh完成格式转换

额外兼容性优化

原脚本wget调用未给URL加引号,特殊字符可能被shell错误解析,建议将wget行修改为:

wget --no-check-certificate --glob=on "$t1?$saug" --output-document="$writ"

修改后完整可跨平台运行脚本

set inp = 1
set reg = 1

set year = 2020
 
#set jul_day = `date +"%j"`
set jul_day=152

set i=205

while ($i>33)
    # 兼容BSD/GNU date
    if ( `date --version >/dev/null 2>&1` ) then
        set query_day=`date -d "$i days ago" +"%Y-%m-%d"`
    else
        set query_day=`date -v -"$i"d +"%Y-%m-%d"`
    endif
    echo $query_day
    echo $jul_day

    if ($inp == 1) then
        set n1 = 'MODIS_Terra'
        set out1 = '.terra.250m.tif'
    else if ( $inp == 2 ) then
        set n1 = 'MODIS_Aqua'
        set out1 = '.aqua.250m.tif'
    else if ( $inp == 3 ) then
        set n1 = 'VIIRS_SNPP'
        set out1 = '.viirs.250m.tif'
    endif

    set t1 = 'https://wvs.earthdata.nasa.gov/api/v1/snapshot'
    set t1a = 'REQUEST=GetSnapshot&TIME='

    if ( $reg == 1 ) then
        # NE Greenland
        set t2 = 'T00:00:00Z&BBOX=200704,-2009088,1093632,-317440&CRS=EPSG:3413&LAYERS='
        set t3 = '_CorrectedReflectance_TrueColor,Coastlines&WRAP=day,x&FORMAT=image/tiff&WIDTH=4458&HEIGHT=8120'
        set out_f = 'Fram_Strait'
    endif

    set saug = $t1a$query_day$t2$n1$t3
    echo $saug
    set writ = $out_f$year$jul_day$out1

    wget --no-check-certificate --glob=on "$t1?$saug" --output-document="$writ"

    @ jul_day ++
    @ i --
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:45:03