基本上我想从bash做这样的事情。 如果目录中存在文件,重命名,移动,无论什么 如果不存在,则每 60 秒循环一次:
# Create ~/bin
cd ~/
if dir ~/bin does not exist
then mkdir ~/bin
#!/bin/bash
# Create ~/blahhed && ~/blahs
if dir ~/blahhed does not exist
then mkdir ~/blahhed
if dir ~/blahs does not exist
then mkdir ~/blahs
# This will copy a file from ~/blahhed to ~/blahs
if ~/blahhed/file exists
then mv ~/blahhed/file ~/blahs/file
rm ~/blahhed/file
else loop for 60s
# This appends the date and time
# to the end of the file name
date_formatted=$(date +%m_%d_%y-%H,%M,%S)
if ~/blahs/file does exist
then mv ~/blahs/file ~/blahs/file.$date_formatted
rm ~/blahs/file
else loop for 60s
好的,我像这样重写了它,我在这里走在正确的轨道上吗?
# Create ~/bin
cd ~/
if [! -d ~/bin]; then
mkdir ~/bin
if [ -d ~/bin]; then
#!/bin/bash
# Create ~/blahhed && ~/blahs
if [! -d ~/blahhed]; then
mkdir ~/blahhed
if [! -d ~/blahs]; then
mkdir ~/blahs
# This will copy a file from ~/blahhed to ~/blahs
while if [ -d ~/blahhed/file]; then
do
mv ~/blahhed/file ~/blahs/file
rm ~/blahhed/file
continue
# This appends the date and time
# to the end of the file name
date_formatted=$(date +%m_%d_%y-%H,%M,%S)
if [! -d ~/blahs/file]; then
mv ~/blahs/file ~/blahs/file.$date_formatted
rm ~/blahs/file
sleep 60 seconds
你可以使用 watch(1),它能够每 N 秒运行一次程序或脚本。
要每隔几分钟 (不是秒) 运行一些脚本, 或者每隔几小时或几天, 使用一些 crontab(5) 条目。要在某个给定(相对或绝对)时间运行它,请考虑 at(1)(您可以在 shell 终端中与此处的一些文档一起使用,等等...)。
但是,要在文件存在或更改时执行命令,您可以使用 make(1)(您可以从 watch
运行);该命令可以在Makefile
中配置(参见 GNU make 的文档)
如果你真的关心文件的出现或更改(以及对这些更改做一些事情),请考虑使用基于 inotify(7) 的工具,例如 incrond
with incrontab(5)
要测试目录或文件的存在性,请使用 test(1) 通常拼写为[
,例如
## test in a script if directory ~/foo/ exist
if [ -d ~/foo/ ]; then
echo the directory foo exists
fi
上面空间很重要。您可以使用[ -d "$HOME/foo/" ]
看起来你想模仿 logrotate(8)。另请参阅 syslog(3) 库函数和 logger(1) 命令。
要调试你的 bash 脚本,请启动它(有关详细信息,请参阅 execve(2) 和 bash(1) - 暂时,在调试时)
#!/bin/bash -vx
并使用chmod a+x foo.sh
使您的foo.sh
脚本可执行
要停止执行某个脚本几秒钟,请使用 sleep(1)
mkdir(1) 命令接受-p
(如果目录已经存在,则不会创建目录)。 mv(1) 也有很多选项(包括备份选项)。
要搜索文件树中的某些文件,请使用 find(1)。要搜索文件中的某些内容,请使用 grep。我也喜欢阿克
另请阅读高级 Bash 脚本指南和(如果用 C 编码......)高级Linux编程以及GNU bash的文档(例如shell内置和控制语句)。
您是否考虑过使用一些版本控制系统,例如 git?管理源文件(包括 shell 脚本)的演变很有用
我已经看到了与您要求的解决方案类似的解决方案,但是使用带有 find -mmin 1
的 crontab 将搜索指定位置内 modtime <= 60 秒的任何文件。
类似这些内容(未经测试):
$ -> vi /tmp/file_finder.sh
# Add the following lines
#!/bin/bash
find /path/to/check -mmin 1 -type -f | while read fname; do
echo "$fname"
done
# Change perms
$ -> chmod 755 /tmp/file_finder.sh
$ -> crontab -e
* * * * * /tmp/file_finder.sh
有了上述内容,您现在已经将 cron 设置为每分钟运行一次,并启动一个脚本,该脚本将在给定目录中搜索 modtime <= 60 秒(新的或更新的)的文件。
警告:您应该查找修改时间不超过 5 分钟的文件,这样您就不会考虑可能仍在编写中的文件。
我想你回答了自己(有点)
一些建议:
1-使用while循环,最后添加sleep 60
2-将过程写入文件(例如test1)然后
watch -n 60 ./test1