linux下新建一个print hello world的脚本程序,如下所示:
~/boke---> vim hello.sh
~/boke---> cat hello.sh
#!/bin/bash
#this is hello script
echo 'hello, I am yLiu'
先来查看hello.sh的文件属性,如下所示:
~/boke---> ll hello.sh
-rw-r--r-- 1 yliu sw 60 Apr 13 16:16 hello.sh
可以发现hello.sh的文件所有者、所有者所在组及其他用户都没有执行的权限,即没有x权限。
- 方法1:指定shell解释器来运行(代码
#!/bin/bash
可不写)
~/boke---> bash hello.sh
hello, I am yLiu
- 方法2:添加文件x权限来运行;
#添加执行权限,3类对象,2种方法
~/boke---> chmod u+x hello.sh #给所有者+执行权限
~/boke---> ll hello.sh
-rwxr--r-- 1 yliu sw 60 Apr 13 16:16 hello.sh
~/boke--->
~/boke---> chmod g+x hello.sh #给所有者所在组+执行权限
~/boke---> ll hello.sh
-rwxr-xr-- 1 yliu sw 60 Apr 13 16:16 hello.sh
~/boke--->
~/boke---> chmod o+x hello.sh #给其他人+执行权限
~/boke---> ll hello.sh
-rwxr-xr-x 1 yliu sw 60 Apr 13 16:16 hello.sh
~/boke--->
~/boke---> chmod a+x hello.sh #给所有人+执行权限 等于前面3条命令的和
~/boke---> ll hello.sh
-rwxr-xr-x 1 yliu sw 60 Apr 13 16:16 hello.sh
#一般使用最后一种方法即chmod a+x hello.sh来添加权限即可
#添加权限后执行该脚本程序,指定脚本路径即可运行(代码```#!/bin/bash```必须写)
~/boke---> ./hello.sh
hello, I am yLiu
- 方法3:利用命令.号来运行,该脚本无可执行权限也可运行,此方法最简单;
~/boke---> chmod a-x hello.sh #取消所有人的执行权限
~/boke---> ll hello.sh
-rw-r--r-- 1 yliu sw 60 Apr 13 16:16 hello.sh
~/boke--->
~/boke---> . hello.sh #使用.命令执行
hello, I am yLiu
~/boke--->
- 方法4:此方法为方法2的扩展,添加执行x权限后放入系统环境变量目录中,即可在任何目录下运行改脚本,并无需指定脚本路径。
~/boke---> echo $PATH #查看系统环境变量$PATH目录
/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
~/boke---> chmod a+x hello.sh #添加x权限
~/boke---> sudo cp hello.sh /usr/bin/ #拷贝脚本至$PATH中的一个
~/boke---> ll /usr/bin/he #确认拷贝成功
head heimdal-krb5-config hello.sh helpviewer hexdump
~/boke---> ll /usr/bin/hello.sh #检查脚本x权限
-rwxr-xr-x 1 root root 60 Apr 13 16:45 /usr/bin/hello.sh
~/boke--->
~/boke---> cd ~ #切换至任意目录
~---> he #tab键匹配生效
head heimdal-krb5-config hello.sh help helpviewer hexdump
~---> hello.sh #正确执行该脚本
hello, I am yLiu
~--->