在文件夹打开或内容更改时运行 bash 脚本
如果我有一个存储在文件夹中的 bash 脚本,是否可以在打开文件夹时运行它?
第一个示例
假设我在 shared 文件夹中有脚本 s
(例如在 Dropbox)foo
每当用户键入
cd /path/to/foo
我想要显示的消息时,就说Hello,visitor!
。我怎样才能做到这一点(如果可以的话)?
我已经看到 这个问题,但我没有找到有关答案中所说内容的示例。
如果这不能以简单的方式实现,那么相同的脚本是否可以在检测到文件夹内容更改时运行,或者我是否需要第二个脚本来检查然后运行前者?
第二个示例
相同的脚本 s
位于同一个 shared foo
文件夹中。如果我在 foo
文件夹中执行类似操作
touch test.txt
,我希望显示另一条消息,比如说 您已创建一个新文件!
或相应地将文件重命名为该文件夹的标准。
使用此配置,我必须确保进入该文件夹的人都会触发脚本,但我无法重新定义任何内置函数,也无法修改 bash 文件。
If I have a bash script which is stored in a folder, is it possible to have it running on folder opening?
First example
Suppose I have the script s
in the shared folder (for example on Dropbox) foo
and whenever a user types
cd /path/to/foo
I want to display a message, let's say Hello, visitor!
. How could I do that (if I can)?
I've already seen this question but I found no examples about what it is said in the answers.
If that's not achievable in a simple way, is it possible for the same script to run upon detecting folder content changes or do I need a second script to check that and then run the former?
Second example
Same script s
located in the same shared foo
folder. If I do something like
touch test.txt
while in the foo
folder, I'd like to have another message displayed, let's say You have created a new file!
or rename the file accordingly to a standard for that folder.
With this configuration I have to make sure that whoever enters that folder triggers the script but I'm not able to redefine any builtin function nor modify bash files.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种方法是,将类似的内容添加到 .bashrc 中:
请注意,我使用了
realpath
,它可能在您的系统上不可用。它的目的是避免检测从“~”到“/home/user”再到“../user”等的更改目录。该示例使用简单的检测来检测用户何时更改为 Git 工作树根并使用 Git 本身来显示该树的状态。
检测变化:
您可以使用 find 来调整它。我建议使用一些限制器(如下所示的 -maxdepth 和 -mmin)来防止这成为资源消耗。我确信使用 inotify 时会有更多的性能选项(但我不确定它们是否可以轻松地从 bash 访问)。
Another approach would be, adding something like this to .bashrc:
Note that I used
realpath
which may not be available on your system. It was intended to avoid detecting changed directories from "~" to "/home/user" to "../user" etc.The sample uses a simple detection to detect when the user changes to a Git worktree root and uses Git itself to display the status for that tree.
Detecting change:
You could tweak it using find. I recommend using some limiters (-maxdepth and -mmin shown below) to prevent this from becoming a resource drain. I'm sure there will be much more performant options when using inotify (but I'm not sure whether they are easily accessed from bash).
这可能不是一个好主意,但是是的,您可以按照您所描述的进行操作。对于用户的
.bashrc
,您可以添加以下内容:(不用说,这有很多警告和限制。您正在修改基本的 Bash 行为,这通常不是一个好主意。 )
This probably isn't a good idea, but yes, you can do what you describe. To the user's
.bashrc
, you can add this:(Needless to say, there are lots of caveats and limitations to this. You're modifying a basic Bash behavior, which is generally not a great idea.)