shell脚本的建立与执行

本文介绍Linux环境下Shell脚本的基础知识,包括脚本开头的解释器声明、注释的使用方法、不同执行方式的特点及注意事项。通过具体示例帮助理解如何运行脚本。

脚本的开头(第一行):

规范的脚本在脚本的第一行会指出由哪个程序(解释器)来执行脚本中的内容
在linux bash的编程中一般为:

#!/bin/bash
或 #!/bin/sh

‘#!’被称为幻数,用来指出执行脚本所用的解释器,并且此行必须用在第一行,若不是脚本第一行则其就是注释行

sh与bash的区别:
[root@localhost SHELL]# ls -l /bin/sh
lrwxrwxrwx. 1 root root 4 Jan 15 2016 /bin/sh -> bash
[root@localhost SHELL]# ll /bin/bash
-rwxr-xr-x. 1 root root 960368 Jan 29 2014 /bin/bash
[root@localhost SHELL]#

sh为bash的软连接,但又有区别;
当使用/bin/sh执行脚本不正常的时候,可以使用/bin/bash执行

也可以不加#!/bin/bash,是因为linux系统默认/bin/bash

脚本的注释:

在shell脚本中,跟在(#)号后面的内容表示注释,用来对脚本进行解释说明;
注释可以自成一行,也可以跟在脚本命令后面与命令在同一行。

shell脚本的执行:

在执行shell脚本之前,它会先加载系统环境变量ENV(该变量指定了环境文件,通常是 .bashrc , .bash_profile , /etc/bashrc , /etc/profile等),然后执行脚本。

特殊:设置定时任务时,最好把系统环境变量在定时任务脚本中重新定义,否则,一些系统环境变量将不被加载

shell脚本的执行方式:
<1>bash script-name 或 sh script-name(推荐使用)
该方法是当脚本文件本身没有可执行权限时,或者文件开头没有指定解释器时常使用的方法

[root@localhost SHELL]# vim test.sh
[root@localhost SHELL]# cat test.sh 
echo 'hello world'
[root@localhost SHELL]# sh test.sh 
hello world
[root@localhost SHELL]# 
[root@localhost SHELL]# cat >test1.sh  //用cat向文件中写内容
echo 'ni hao, ming tian'
^C
[root@localhost SHELL]# cat test1.sh 
echo 'ni hao, ming tian'
[root@localhost SHELL]# /bin/sh test1.sh 
ni hao, ming tian
[root@localhost SHELL]# /bin/bash test1.sh 
ni hao, ming tian
[root@localhost SHELL]# 

<2>path/script-name 或 ./script-name (当前路径下执行脚本)
该方式需要脚本有执行权限

[root@localhost SHELL]# ll
total 8
-rw-r--r-- 1 root root 25 Dec 31 10:55 test1.sh
-rw-r--r-- 1 root root 19 Dec 31 10:50 test.sh
[root@localhost SHELL]# chmod +x test.sh 
[root@localhost SHELL]# ll
total 8
-rw-r--r-- 1 root root 25 Dec 31 10:55 test1.sh
-rwxr-xr-x 1 root root 19 Dec 31 10:50 test.sh
[root@localhost SHELL]# ./test.sh 
hello world
[root@localhost SHELL]# 

<3>source script-name 或 . script-name <注意 . 号>

[root@localhost SHELL]# source test.sh 
hello world
[root@localhost SHELL]# . test.sh 
hello world
[root@localhost SHELL]# 

<4>用重定向或者管道来执行

[root@localhost SHELL]# sh <test1.sh 
ni hao, ming tian
[root@localhost SHELL]# cat test1.sh | sh
ni hao, ming tian
[root@localhost SHELL]#

例题:
这里写图片描述

其执行结果为<空>,即就是没有输出结果
原因:echo $user是父shell,而test.sh是子shell,父shell不能直接继承子shell的变量,函数等,反之可以

如果希望可以继承(即让父继承子),用source或者点号执行就可以

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值