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

Léo*_* 준영 2 bash file-permissions

我可以运行具有000权限的Bash函数并不是完全严格的,但差不多.我的代码是:

#!/bin/bash
function hello {
echo Hello! }
Run Code Online (Sandbox Code Playgroud)

hello-file有权限:

-r--------  1 UnixBasics hello_file
Run Code Online (Sandbox Code Playgroud)

最初,我使用当前权限键入:

$ . ./hello_file;hello
Run Code Online (Sandbox Code Playgroud)

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

$ chmod 000 hello_file
$ . ./hello_file;hello                                             [1]
-bash: ./hello_file: Permission denied 
Hello!
Run Code Online (Sandbox Code Playgroud)

它给出了一个错误,但它不会停止运行该函数.我不明白.我现在取消设置hello-function:"unset hello".我收到错误:

-bash: ./hello_file: Permission denied
-bash: hello: command not found
Run Code Online (Sandbox Code Playgroud)

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

Jul*_*ano 11

没有运行脚本,而是在寻找(包括)它.要获取脚本,您只需要读取权限.

顺便说一句,功能只是存在,他们没有权限.一旦获取文件并定义了函数,您就可以根据需要运行它.


更新:

为什么我第一次没有得到它们?它与缓存,缓冲区或类似的东西有关吗?

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

为什么我可以用000权限运行Bash脚本[1]?

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

$ . ./hello_file;hello                                             [1]
-bash: ./hello_file: Permission denied 
Hello!
Run Code Online (Sandbox Code Playgroud)

您在一个命令行中执行了两个命令.采购失败,"许可被拒绝"."你好!" 输出来自先前的文件来源.当你取消设置并再次尝试相同的命令行时,你就自己证明了这一点.

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

$ chmod +x hello_file
$ ./hello_file           # note: executed, not sourced
$ hello
-bash: hello: command not found
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 5

最可能的解释是,在受保护之前运行hello_file并且已经创建了该函数.然后你保护你的脚本(你在命令中说100但在文中提到000).

那么,脚本将无法运行.但是hello()仍然是从你之前的运行中定义的.

尝试打开一个新的shell或只是执行unset hello.