【问题标题】:understanding a ksh script part of了解 ksh 脚本的一部分
【发布时间】:2010-01-07 19:22:50
【问题描述】:

有人可以帮我理解下面这段代码,它决定了从数据库中挑选数据的开始日期和结束日期。

# Get the current time as the stop time.
#
stoptime=`date +"%Y-%m-%d %H:00"`
if test $? -ne 0
then
   echo "Failed to get the date"
   rm -f $1/.optpamo.pid
   exit 4
fi

#
# Read the lasttime file to get the start time
#
if test -f $1/optlasttime
then
   starttime=`cat $1/optlasttime`
   # if the length of the chain is zero
   # (lasttime is empty) It is updated properly
   # (and I wait for the following hour)
   if test -z "$starttime"
   then
      echo "Empty file lasttime"
      echo $stoptime > $1/optlasttime
      rm -f $1/.optpamo.pid
      exit 5
   fi
else
   # If lasttime does not exist I create, it with the present date
   # and I wait for the following hour
   echo "File lasttime does not exist"
   echo $stoptime > $1/optlasttime
   rm -f $1/.optpamo.pid
   exit 6
fi

谢谢

【问题讨论】:

  • 您不清楚哪些方面?
  • 您的脚本 sn-ps 的格式似乎有问题。如果您突出显示它们并按下编辑器上方带有0101 图标的按钮,它应该将它们格式化为代码。
  • 脚本注释已经够好了,还有什么不明白的地方?

标签: shell scripting ksh


【解决方案1】:

脚本会检查指定为参数 ($1) 的目录中是否存在名为 optlasttime 的非空文件。如果是,则脚本成功退出(状态0)。如果文件不存在或为空,则将格式为2010-01-07 14:00 的当前小时写入文件,从参数目录中删除另一个名为.optpamo.pid 的文件,脚本退出失败(状态5 或@987654327 @)。

这个脚本显然是一个被某个外部进程调用的实用程序,您需要参考它才能完全理解。

【讨论】:

    【解决方案2】:

    1.) 将停止时间设置为当前时间

    2.) 检查文件 $1/optlasttime 是否存在(其中 $1 被传递到脚本中)

     a.) if $1/optlasttime exists it checks the contents of the file (which it is assumed that if it does have contents it is a timestamp)
    
     b.) if $1/optlasttime does not exist it populates the $1/optlasttime file with the stoptime. 
    

    【讨论】:

    • 感谢各位的解释。我可以手动指定日期时间(特定时期)以获取该特定时期的数据。我的意思是我可以将代码中的停止时间指定为 2010-01-03 15:00 并将开始时间指定为 2010-01-04 02:00 并像 ./scriptname 这样运行整个脚本吗?
    • 是的,您可以根据需要对值进行硬编码。或者您可以将其设置为允许从命令行为 $1 和 $2 发出开始和停止时间:./scriptname "2010-01-04 02:00" "2010-01-04 04:00"跨度>
    【解决方案3】:

    我将其中的一个小 sn-p 复制并粘贴到我称为 test.ksh 的文件中

    stoptime=`date +"%Y-%m-%d %H:00"`
    if test $? -ne 0
    then
       echo "Failed to get the date"
       rm -f $1/.optpamo.pid
       exit 4
    fi
    

    然后我在命令行运行它,如下所示:

    zhasper@berens:~$ ksh -x ./temp.ksh 
    + date '+%Y-%m-%d %H:00'
    + stoptime='2010-01-08 18:00'
    + test 0 -ne 0
    

    ksh 的-x 标志使它在执行时完整地打印出每个命令行。将您在此处看到的内容与上面 shell 脚本的 sn-p 进行比较,您应该可以了解 ksh 是如何解释文件的。

    如果你在整个文件上运行它,你应该对它的作用有一个很好的感觉。

    要了解更多,可以阅读man ksh,或在线搜索ksh scripting tutorial

    与我们简单地告诉你脚本的作用相比,这三件事应该能帮助你学到更多东西。

    【讨论】:

    • 感谢您的建议。是否有可以在其中运行测试命令/脚本的在线 unix 环境?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多