【问题标题】:Can't Get variables to update from one sh script to another无法获取变量以从一个 sh 脚本更新到另一个
【发布时间】:2013-03-02 05:16:59
【问题描述】:

我正在尝试创建上次运行文件的记录,并在下次执行脚本文件时使用该时间。所以我有两个文件,testlastrun.shtestmyfile.sh,我在其中声明了一个变量供另一个文件使用。但是对于我的生活,我似乎无法让它发挥作用。

文件 testlastrun.sh

#!/bin/sh

#prepare range of dates for getting data for redemption protocol
source testmyfile.sh
echo "current date is : " `date +'%Y-%m-%d %H:%M:%S'`
enddate=`date -d "+1 hour" '+%Y-%m-%d %H:%M:%S'`
echo "the end date is : " $enddate
startdate=$LASTRUNTIME
echo "start date:" $startdate
LASTRUN=$enddate
export LASTRUN 
echo "LASTRUN variable is : " $LASTRUN

文件 testmyfile.sh

#!/bin/sh

echo "LASTRUN variable is currently set to : " $LASTRUN
LASTRUNTIME=$LASTRUN
export LASTRUNTIME

我觉得我已经阅读了关于 bash 脚本和变量的每一篇文章,但对于我的一生来说,我无法让它发挥作用。所以,如果你们中的任何一位超级聪明的 bash 专家可以帮助我,我将不胜感激。 :-)

【问题讨论】:

    标签: bash environment-variables


    【解决方案1】:

    我认为您的错误来自您希望 export 更改脚本的 parent 环境这一事实。 export 语句仅告诉 shell 使该变量可用于 child 环境。

    您的脚本中的export 没有任何作用,因为您没有从该脚本生成任何新脚本(您正在获取该脚本,这相当于包含该文件)。

    您应该将信息写入文件并在必要时将其读回。

    【讨论】:

    • 谢谢。这就是我想要完成的事情,并且在过去的无数个小时里一直在绞尽脑汁想弄清楚。
    【解决方案2】:

    只是为了他人的利益,这就是我解决这种情况的方法。我将值写入文本文件(仅包含值),然后在脚本开头读取文件。这是我用来完成它的代码:

    #!/bin/sh
    
    #reads the file testmyfile.txt and sets the variable LASTRUNTIME equal to the contents of the text file
    LASTRUNTIME=`head -n1 testmyfile.txt |tail -1`
    echo "the last time this file was executed was : " $LASTRUNTIME
    
    #shows the current server time on the terminal window
    currentdate=`date +'%Y-%m-%d %H:%M:%S'`
    echo "current date is : " $currentdate
    
    #sets the variable 'enddate' equal to the current time +1 hour
    enddate=`date -d "+1 hour" '+%Y-%m-%d %H:%M:%S'`
    echo "the end date is : " $enddate
    
    #sets the variable 'startdate' equal to the variable LASTRUNTIME
    startdate=$LASTRUNTIME
    echo "start date:" $startdate
    
    #creates and sets variable LASTRUN equal to the current date and time
    LASTRUN=$currentdate
    echo "LASTRUN variable is : " $LASTRUN
    
    #updates the file 'testmyfile.txt' to store the last time that the script routine was executed
    echo "$LASTRUN" > '/home/user/testmyfile.txt'
    

    我就是这样做的。谢谢加维。感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2022-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多