AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / ubuntu / 问题 / 893019
Accepted
Ignacio
Ignacio
Asked: 2017-03-15 10:26:59 +0800 CST2017-03-15 10:26:59 +0800 CST 2017-03-15 10:26:59 +0800 CST

如果那里有文件,则监视文件夹并运行命令?

  • 772

我想要我的 Ubuntu 显示器Folder A。如果那里有.sh文件,我想将该文件移动到Folder B后台并在后台运行它。这可能吗?我应该用什么来实现它?

command-line
  • 2 2 个回答
  • 15218 Views

2 个回答

  • Voted
  1. Best Answer
    Jacob Vlijm
    2017-03-15T21:33:38+08:002017-03-15T21:33:38+08:00

    你有几个选择:

    1. 使用 inotifywait

    #!/bin/bash
    # set path to watch
    DIR="/path/to/sourcedir"
    # set path to copy the script to
    target_dir="/path/to/targetdir"
    
    inotifywait -m -r -e moved_to -e create "$DIR" --format "%f" | while read f
    
    do
        echo $f
        # check if the file is a .sh file
        if [[ $f = *.sh ]]; then
          # if so, copy the file to the target dir
          mv "$DIR/$f" "$target_dir"
          # and rum it
          /bin/bash "$target_dir/$f" &
        fi
    done
    

    inotifywait 的解释

    设置选项

    要连续记录,您需要设置选项-m:

    来自man inotifywait:

    -m, --monitor
        Instead of exiting after receiving a single event, execute indefinitely. The default behaviour is to exit after the first event occurs. 
    

    要递归记录,您需要设置选项-r:

    -r, --recursive
        Watch all subdirectories of any directories passed as arguments. Watches will be set up recursively to an unlimited depth. Symbolic links are not traversed. Newly created subdirectories will also be watched. 
    

    如果您不需要递归监视,请删除该选项。

    活动

    此外,您需要指定要触发的事件:

    EVENTS
           The following events are valid for use with the -e option:
    
           access A  watched  file  or  a file within a watched directory was read
                  from.
    
           modify A watched file or a file within a watched directory was  written
                  to.
    
           attrib The metadata of a watched file or a file within a watched direc‐
                  tory was modified.  This includes timestamps, file  permissions,
                  extended attributes etc.
    
           close_write
                  A  watched file or a file within a watched directory was closed,
                  after being opened in writeable mode.  This does not necessarily
                  imply the file was written to.
    
           close_nowrite
                  A  watched file or a file within a watched directory was closed,
                  after being opened in read-only mode.
    
           close  A watched file or a file within a watched directory was  closed,
                  regardless  of  how  it  was opened.  Note that this is actually
                  implemented  simply  by  listening  for  both  close_write   and
                  close_nowrite, hence all close events received will be output as
                  one of these, not CLOSE.
    
           open   A watched file or a file within a watched directory was opened.
    
           moved_to
                  A file or directory was moved into a  watched  directory.   This
                  event  occurs  even  if the file is simply moved from and to the
                  same directory.
    
           moved_from
                  A file or directory was moved from a  watched  directory.   This
                  event  occurs  even  if the file is simply moved from and to the
                  same directory.
    
           move   A file or directory was moved from or to  a  watched  directory.
                  Note  that  this is actually implemented simply by listening for
                  both moved_to and moved_from, hence all  close  events  received
                  will be output as one or both of these, not MOVE.
    
           move_self
                  A  watched  file  or  directory was moved. After this event, the
                  file or directory is no longer being watched.
    
           create A file or directory was created within a watched directory.
    
           delete A file or directory within a watched directory was deleted.
    
           delete_self
                  A watched file or directory was deleted.  After this  event  the
                  file  or  directory  is no longer being watched.  Note that this
                  event can occur even if it is not explicitly being listened for.
    
           unmount
                  The filesystem on which a watched file or directory resides  was
                  unmounted.   After this event the file or directory is no longer
                  being watched.  Note that this event can occur even if it is not
                  explicitly being listened to.
    

    您需要在要触发的每个事件之前添加-e:

    -e moved_to -e create
    

    当然,您可以从列表中设置任何事件触发器。

    使用选项--format "%f",我们使命令输出文件名,我们将使用它来复制和运行文件,并结合设置的路径。

    如何使用

    1. 使用 apt 安装 inotify-tools:

      sudo apt install inotify-tools
      
    2. 将脚本复制到一个空文件中,另存为watch_dir.sh

    3. 在脚本的头部,设置要监视的目录并将脚本复制到
    4. 运行它,它开始监视您的目录。

    2.使用python

    无需安装任何额外的东西,我们可以使用一个小的 python 脚本来做同样的事情:

    #!/usr/bin/env python3
    import subprocess
    import os
    import time
    import shutil
    
    source = "/path/to/sourcedir"
    target = "/path/to/targetedir"
    files1 = os.listdir(source)
    
    while True:
        time.sleep(2)
        files2 = os.listdir(source)
        # see if there are new files added
        new = [f for f in files2 if all([not f in files1, f.endswith(".sh")])]
        # if so:
        for f in new:
            # combine paths and file
            trg = os.path.join(target, f)
            # copy the file to target
            shutil.move(os.path.join(source, f), trg)
            # and run it
            subprocess.Popen(["/bin/bash", trg])
            print(trg)
        files1 = files2
    

    如何使用

    1. 将脚本复制到一个空文件中,另存为watch_dir.py
    2. 在脚本的头部,设置要监视的目录并将脚本复制到 ( source, target)
    3. 运行它,它开始监视您的目录。

    笔记

    上面的两个选项都假定脚本不需要任何参数,但显然在这样的设置中就是这种情况。

    • 8
  2. david
    2020-07-12T14:40:55+08:002020-07-12T14:40:55+08:00

    这里是递归树遍历的另一个版本......

    #!/usr/bin/env python3
    import subprocess
    import os
    import time
    import shutil
    import threading
    
    source = "/home/pi/Pictures/2020/"
    
    def tree_walk(path):
        if os.path.isfile(path):
        if path.endswith("jpg"):
            subprocess.Popen(["/home/pi/git/rpi_scripts/telegram/tg_send_pic.sh", path])
            subprocess.Popen(["rm", path])
        elif path.endswith("mp4"):
            subprocess.Popen(["/home/pi/git/rpi_scripts/telegram/tg_send_video.sh", path])
            subprocess.Popen(["rm", path])
        else:
            print("other files...", path)
    elif os.path.isdir(path):
        items = os.listdir(path)
        for i in items:
            trg = os.path.join(path, i)
            tree_walk(trg)
    else:
        print(path, "spec file: socket, FIFO, device file etc.")
    
    tree_walk(source)
    #try:
    #thread = threading.Timer(3, tree_walk(source))
    #thread.start()
    #except KeyboardInterrupt:
    #    print("end")
    
    • 0

相关问题

  • 如何从命令行仅安装安全更新?关于如何管理更新的一些提示

  • 如何从命令行刻录双层 dvd iso

  • 如何从命令行判断机器是否需要重新启动?

  • 文件权限如何工作?文件权限用户和组

  • 如何在 Vim 中启用全彩支持?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何运行 .sh 脚本?

    • 16 个回答
  • Marko Smith

    如何安装 .tar.gz(或 .tar.bz2)文件?

    • 14 个回答
  • Marko Smith

    如何列出所有已安装的软件包

    • 24 个回答
  • Marko Smith

    无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗?

    • 25 个回答
  • Martin Hope
    Flimm 如何在没有 sudo 的情况下使用 docker? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    Ivan 如何列出所有已安装的软件包 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    La Ode Adam Saputra 无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗? 2010-11-30 18:12:48 +0800 CST
  • Martin Hope
    David Barry 如何从命令行确定目录(文件夹)的总大小? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher “以下软件包已被保留:”为什么以及如何解决? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford 如何删除 PPA? 2010-07-30 01:09:42 +0800 CST

热门标签

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve