0

我想编写一个 bash 脚本,它将time.txt在登录用户的主目录中创建一个文件,将时间放入其中并每n秒更新一次,直到脚本停止。

到目前为止,我有:

#! /bin/bash

do
echo "Current time" > time.txt
chmod +rwx "time.txt"

time=$(date + "%T")
echo "$time" >> time.txt

sleep 2;

watch -n 1 head -n2 time.txt.

done

剧本不新鲜。它给出了正确的日期,但只有一次。我究竟做错了什么?

4

2 回答 2

2

该脚本在语法上无效。-块没有whilefor循环。添加一个循环将dodone

while true; do
    date +%T >> time.txt
    sleep 2
done

你会想要摆脱watch循环内的调用。watch本身就是一个永无止境的循环,它将阻止连续的迭代运行。

于 2018-07-18T01:02:39.700 回答
0

你应该做:

while :; do
    # I'm assuming you want to see the date displayed on the terminal too.
    echo -e "Current time.\n$(date +%T)" | tee time.txt | sed '/Current time/d'
    sleep 2
done

:是命令的简写true

于 2018-07-18T04:55:13.453 回答