Linux中如何设置文件跳转,点击foo.txt时自动执行bar.sh脚本
实现方案
以下提供多场景的实现方案,优先给出原生shell和Python实现:
方案1:Linux桌面原生shell方案(无额外依赖)
利用Linux桌面的.desktop入口实现,伪装性最强,操作最简单:
- 先给目标脚本加执行权限,替换为你自己的实际路径:
chmod +x /absolute/path/to/bar.sh - 新建名为
foo.txt.desktop的文件,写入以下内容:[Desktop Entry] Type=Application Name=foo.txt Exec=/absolute/path/to/bar.sh Icon=text-plain Terminal=false - 给desktop文件加执行权限:
chmod +x foo.txt.desktop
Linux桌面环境默认会隐藏.desktop后缀,最终显示的文件名为foo.txt,图标和普通文本文件完全一致,点击就会自动执行bar.sh。
方案2:跨平台Python监听方案
支持Windows/macOS/Linux全平台,通过监听文件打开事件触发执行:
- 先安装依赖库:
pip install watchdog - 新建监听脚本
watch_foo.py,替换其中的路径为你自己的实际路径:import os import subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class FooOpenHandler(FileSystemEventHandler): def on_opened(self, event): if not event.is_directory and os.path.basename(event.src_path) == "foo.txt": # Windows环境下可替换为对应的bat执行命令 subprocess.Popen(["bash", "/absolute/path/to/bar.sh"], shell=False) if __name__ == "__main__": # 替换为foo.txt所在的文件夹的绝对路径 watch_dir = "/absolute/path/to/folder/of/foo.txt" observer = Observer() observer.schedule(FooOpenHandler(), watch_dir, recursive=False) observer.start() try: while observer.is_alive(): observer.join(1) except KeyboardInterrupt: observer.stop() observer.join() - 将该脚本设置为开机自启,后续只要
foo.txt被打开,就会自动触发执行bar.sh。
方案3:Windows原生批处理方案
如果你是Windows系统,可以直接修改txt后缀的关联程序实现:
- 新建
txt_handler.bat批处理脚本,内容如下:@echo off if "%~nx1"=="foo.txt" ( rem 这里替换为你的bar.sh执行命令,WSL环境可写 wsl /path/to/bar.sh call C:\path\to\bar.bat ) else ( rem 其他txt文件正常用系统记事本打开,可替换为你常用的文本编辑器路径 notepad.exe %1 ) - 任意选择一个txt文件,右键 -> 打开方式 -> 选择其他应用 -> 选中上面的
txt_handler.bat,勾选「始终使用此应用打开.txt文件」即可。
内容的提问来源于stack exchange,提问作者random_hooman
相关产品推荐
相关产品推荐

