bash - 为什么我可以使用 000 权限运行 Bash 函数?

标签 bash file-permissions

我可以用 000 权限运行 Bash 函数并不完全正确,但差不多。我的代码是:

#!/bin/bash
function hello {
echo Hello! }

hello 文件具有以下权限:

-r--------  1 UnixBasics hello_file

首先,我使用当前权限输入:

$ . ./hello_file;hello

调整是在运行 bash 脚本之前将 400 权限更改为 000:

$ chmod 000 hello_file
$ . ./hello_file;hello                                             [1]
-bash: ./hello_file: Permission denied 
Hello!

它给出了一个错误,但它并没有停止运行函数。我无法理解。我现在取消设置问候功能:“取消设置你好”。我收到错误:

-bash: ./hello_file: Permission denied
-bash: hello: command not found

为什么我没有第一时间得到它们?它与缓存、缓冲区或类似的东西有关吗?为什么我可以使用 000 权限运行 Bash 脚本[1]?

最佳答案

没有运行脚本,您正在采购(包括)它。要获取脚本源,您只需要读取权限。

顺便说一句,函数只是存在,它们没有权限。获取文件并定义函数后,您可以随意运行它。


更新:

Why did I not get them at the first time? Has it something to do with cache, buffer or something like it?

是的,就像 Pax 回答的那样,hello 可能是以前从文件的先前来源那里定义的。您可能对 sourcing ("."内置命令) 的作用感到困惑。 Sourcing 读取文件并在当前 shell 中运行其所有命令,然后返回到提示符。因此,如果您运行该文件一次,它的函数将在当前 shell 实例中定义,并且它们会一直保留在那里直到您完成该 shell session (或取消设置它们)。

Why can I run the Bash script with 000 permissions [1]?

你不能。请注意,它会出现错误。引用你的输出:

$ . ./hello_file;hello                                             [1]
-bash: ./hello_file: Permission denied 
Hello!

您在一个命令行中执行了两个命令。采购失败并显示“权限被拒绝”。的“你好!”输出来自文件的先前来源。当您取消设置并再次尝试相同的命令行时,您只是自己证明了这一点。

你不能调用那个缓存...这是 shell 的工作方式。您获取另一个文件,其所有定义都包含在当前 shell session 中并保留在那里。如果您实际运行脚本(而不是采购),您应该不会在当前 session 中得到任何残留物。

$ chmod +x hello_file
$ ./hello_file           # note: executed, not sourced
$ hello
-bash: hello: command not found

关于bash - 为什么我可以使用 000 权限运行 Bash 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683994/

相关文章:

bash - 如何判断 "find"命令的输出是否为空?

bash - 如何获取父进程的用户?

Java 抛出 java.io.FileNotFoundException :/dir/file. xlsx "Permission denied"

使用bash复制mysql数据库脚本

macos - Mac OS X "El Capitan": cannot read user set Bash environment variables

linux - 一键部署需要哪些权限设置?

c++ - 程序删除其他用户的文件

android - 在 Android/Unity 上使用 MODE_WORLD_READABLE 共享文件

php - 将上传文件移动到 IIS 中的另一台服务器的权限被拒绝

linux - 如何在kshell中获取前几天的日期