一个程序,它接受一个文件作为文件1和一个以秒为单位的参数2,然后程序将检查是否:
#!/bin/bash
file=$1
sleeptime=$2
bool=true
if [ -e $file ]; then
thetime=$(date -r $file "+%s")
newtime=$(date -r $file "+%s")
while "$bool" = true
do
sleep $sleeptime
newtime=$(date -r $file "+%s")
if [ "$thetime" -ne "$newtime" ]; then
bool=false
echo "Filen $file ble endret"
fi
if [ ! -e $file ]; then
bool=false
echo "Filen $file ble slettet"
fi
done
fi
if [ ! -e $file ]; then
while "$bool" = true
do
sleep $sleeptime
if [ -e $file ]; then
bool=false
echo "Filen $file ble opprettet"
fi
done
fi
答案 0 :(得分:1)
Bash很难进入,为您提供一些指示:
子命令有点棘手,如果表达式包含变量,通常需要在子shell中运行它,而变量由$()
完成,而不是()
({{ 3}})
while
,if
需要通过分号或换行符与do
,then
分开
explained in this SO question与其他语言略有不同,在您的情况下-f
运算符检查文件是常规文件(另请参阅testing conditions in bash)
通常情况下,引用条件中的变量和传递给命令的变量更好,因为它们包含特殊字符(否则将进行评估)
不确定&#34文件的性质是什么?文件没有被更改"声称,但可能最简单的方法是测试它的大小是否发生了变化,一开始-s
运算符检查文件的大小是否大于零
正如在评论中指出的那样,应用程序特定的变量应该按照惯例小写
使用这些调整的代码:
#!/bin/bash
file=$1
sleeptime=$2
while ($(sleep $sleeptime)); do
if [ ! -f "$file" ]; then
touch $file
echo "File $file was created."
elif [ ! -s "$file" ]; then
rm $file
echo "File $file was deleted."
fi
done
答案 1 :(得分:0)
这将是这样的:
#!/bin/bash
file=$1
sleeptime=$2
while :; do
sleep "$sleeptime"
if [ -f "$file" ] ; then
if [ "$file" -nt ".tag.$file" ] ; then
echo "Not removed $file, because it was changed"
else
rm "$file"
rm ".tag.$file"
echo "File $file was deleted."
fi
else
touch "$file"
touch ".tag.$file"
echo "File $file was created."
fi
done
注意:
man test
。