Linux--shell脚本执行方法总结

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
~--->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值