基本上我想从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
答案 0 :(得分:3)
您可以使用能够每 N 秒运行程序或脚本的watch(1)。
要每隔几分钟(而不是几秒钟) - 或每隔几小时或几天运行一些脚本,请使用一些crontab(5)条目。要在某个给定(相对或绝对)时间运行它,请考虑at(1)(您可能在shell终端中使用某些here document等等。)。
但是,要在文件存在或更改时执行命令,您可以使用make(1)(可以从watch
运行);该命令可在Makefile
中配置(请参阅GNU make)
如果您真的关心文件的显示或更改(以及对此类更改执行某些操作),请考虑使用基于inotify(7)的工具,例如incrond
与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脚本,请启动它(-see execve(2)& bash(1)以获取详细信息 - 暂时(在调试时)
#!/bin/bash -vx
并使用foo.sh
chmod a+x foo.sh
脚本可执行
要停止执行某些脚本几秒钟,请使用sleep(1)
mkdir(1)命令接受-p
(如果目录已存在,则不会创建目录)。 mv(1)还有很多选项(包括备份)。
要搜索文件树中的某些文件,请使用find(1)。要搜索文件中的某些内容,请使用grep。我也喜欢ack
另请阅读Advanced Bash Scripting Guide& (如果用C编码......)Advanced Linux Programming以及GNU bash的文档(例如shell内置和控制语句)。
您是否考虑使用某些revision control system git?管理源文件(包括shell脚本)的演变非常有用
答案 1 :(得分:2)
我已经看过类似于您要求的解决方案,但使用crontab与find -mmin 1
一起搜索在指定位置内具有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分钟的文件,这样您就不会考虑可能仍在编写文件的文件。
答案 2 :(得分:1)
我认为你回答了自己(有点)
一些建议:
1-使用while循环,最后添加sleep 60
2-将您的程序写入文件(例如; test1) 然后
watch -n 60 ./test1