首页 > 技术文章 > ./执行shell脚本提示没有权限Permission denied

zhangxl1016 2021-05-18 23:36 原文

错误原因

shell脚本没有可执行权限。
赋予shell脚本可执行权限即可。
例如touch创建test.sh文件,输入以下内容:

[root@localhost demo]# touch test.sh
[root@localhost demo]# ls
test.sh
[root@localhost demo]# ll
total 0
-rw-r--r--. 1 root root 0 May 18 08:20 test.sh
[root@localhost demo]# 

可以看到此时test.sh没有可执行权限。
vim输入:

#!/bin/bash
echo "hello world";
echo "执行的文件名:$0";

执行./test.sh,输出

-rw-r--r--. 1 root root 64 May 18 08:24 test.sh
[root@localhost demo]# ./test.sh
-bash: ./test.sh: Permission denied
[root@localhost demo]# 

执行. test.sh,输出

[root@localhost demo]# . test.sh
hello world
执行的文件名:-bash
[root@localhost demo]# 

执行source test.sh,输出

[root@localhost demo]# source test.sh
hello world
执行的文件名:-bash
[root@localhost demo]# 

执行sh test.sh,输出

[root@localhost demo]# sh test.sh
hello world
执行的文件名:test.sh
[root@localhost demo]# 

执行bash test.sh,输出

[root@localhost demo]# bash test.sh
hello world
执行的文件名:test.sh
[root@localhost demo]# 

赋予test.sh可执行权限,后在执行./test.sh,输出

[root@localhost demo]# chmod 777 test.sh
[root@localhost demo]# ./test.sh 
hello world
执行的文件名:./test.sh
[root@localhost demo]# 

以上可证明. 、sh 、bash 、source在当前bash环境下读取并执行FileName中的命令。该filename文件可以无"执行权限",./在当前bash环境下读取并执行FileName中的命令。该filename文件不可以没有"执行权限"。

扩展

./FileName作用:打开一个子shell来读取并执行FileName中命令。运行一个shell脚本时会启动另一个命令解释器,每个shell脚本有效地运行在父shell(parent shell)的一个子进程里, 这个父shell是指在一个控制终端或在一个xterm窗口中给你命令指示符的进程,shell脚本也可以启动他自已的子进程,这些子shell(即子进程)使脚本并行地,有效率地地同时运行脚本内的多个子任务。

推荐阅读