无法获取变量以从一个脚本更新到另一个脚本

时间:2013-03-14 01:05:09

标签: bash environment-variables

我正在尝试创建上次运行文件的记录,并在下次执行脚本文件时使用该时间。所以我有两个文件, testlastrun.sh testmyfile.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专家可以帮助我,我将非常感激。 : - )

2 个答案:

答案 0 :(得分:1)

我认为您的错误来自于您希望export更改脚本的环境。 export语句仅告诉shell将此变量提供给环境。

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

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

答案 1 :(得分:1)

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

#!/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'

这就是我做到的。谢谢gawi。我很感激帮助。