2009-10-12 60 views
3

我试图制作一个程序,它接受一个参数,一个文件,然后在60秒后检查文件发生了什么。为此,我需要将-e $1的结果存储在变量中,然后在60秒后检查它。我似乎无法使if表达式听我说,我知道这是错误的。出于测试目的,该脚本只是立即打印出比较结果。期待这样的工作示例,我不知道这个小程序有多少个版本。谢谢!这是明天到期的,任何帮助都非常感谢!Bash比较存储的“布尔”值与什么?

#!/bin/bash 
onStartup=$(test -e $1) 
if [ -e "$1" ]; then 
    unixtid1=$(date +"%s" -r "$1") #To check if the file was edited. 
    echo $unixtid1 
fi 
sleep 3 

#Here trying to be able to compare the boolean value stored in the 
#start of the script. True/False or 1 or 0? Now, both is actually printed. 
if [[ $onStartup=1 ]]; then 
    echo "Exists" 
fi 

if [[ $onStartup=0 ]]; then 
    echo "Does not exists" 
fi 

回答

5

使用$?特殊shell变量来获取命令的结果。请记住,0的返回值表示true。这里被修改脚本

#!/bin/bash 
test -e $1 
onStartup=$? 

if [ $onStartup -eq 0 ]; then 
unixtid1=$(date +"%s" -r "$1") #To check if the file was edited. 
echo $unixtid1 
fi 
sleep 3 

#Here trying to be able to compare the boolean value stored in the 
#start of the script. True/False or 1 or 0? 
if [[ $onStartup -eq 0 ]]; then 
echo "Exists" 
else 
echo "Does not exists" 
fi 

你的原始示例试图将test命令的文字输出存储在onStartup变量。 test命令的文字输出是一个空字符串,这就是为什么你没有看到任何输出。