linux-shell编程-1-简介

shell的种类

/bin/sh:Bourne Shell,是UNIX最初使用的 shell,而且在每种 UNIX 上都可以使用。

/bin/bash:Bourne Again Shell,LinuxOS 默认的,它是 Bourne Shell 的扩展。

/sbin/nologin

/bin/dash

/bin/tcsh,是 Linux 提供的 C Shell 的一个扩展版本。

/bin/csh:C Shell,是一种比 Bourne Shell更适合的变种 Shell,它的语法与 C 语言很相似。

查看当前使用的shell

[root@node0 ~]# echo $SHELL

/bin/bash

在一般情况下,人们并不区分 Bourne Shell 和 Bourne Again Shell,所以,像 #!/bin/sh,它同样也可以改为 #!/bin/bash。

#! 告诉系统其后路径所指定的程序即是解释此脚本文件的 Shell 程序。

/bin/sh和/bin/bash是软连接

[root@node0 ~]# ll /bin/bash

-rwxr-xr-x. 1 root root 877480 Jul 24 2015 /bin/bash

[root@node0 ~]# ll /bin/sh

lrwxrwxrwx. 1 root root 4 Jun 2 23:58 /bin/sh -> bash

 

shell脚本扩展名,习惯使用.sh结尾,扩展名并不影响程序执行

运行shell脚本的方法

1、作为可执行程序执行

chmod +x test.sh

相对路径执行:./test.sh

绝对路径执行:/tmp/test.sh

2、作为解释器参数执行

/bin/sh test.sh

这种方式运行shell程序,不需要为脚本增加可执行权限,脚本内可以不写#!/bin/sh

3、使用source执行

source test.sh

sh和source执行的区别

sh执行脚本,脚本在子shell中执行,脚本中的变量不会出现在父shell中

source执行脚本,脚本在当前shell中执行,脚本中的变量会出现在当前shell中

[root@node0 tmp]# cat test.sh

#!/bin/sh

a='abc'

echo '123'

[root@node0 tmp]# sh test.sh

123

[root@node0 tmp]# echo $a #sh执行脚本,脚本在子shell中执行,脚本中的变量不会出现在父shell中

 

[root@node0 tmp]# source test.sh

123

[root@node0 tmp]# echo $a #source执行脚本,脚本在当前shell中执行,脚本中的变量会出现在当前shell中

abc

脚本编程语言和编译型语言的差异

1、像C、C++、JAVA都是编译型语言,这类语言需要编译器将源代码编译为目标代码(二进制文件)

好处:高效

缺点:多运行于底层,处理某些任务较为复杂

2、shell、python是脚本语言,是解释型语言,由解释器读入程序代码并执行,不需要编译

好处:比编译型语言的层级要高,可以轻易的处理一些文件、目录之类的简单任务,而无需很复杂的代码

缺点:运行速度慢、不支持多任务

脚本的跟踪执行

sh –x test.sh

[root@node0 tmp]# sh -x test.sh

+ a=abc

+ echo 123

123

脚本中set –x打开跟踪功能,set +x关闭跟踪功能

[root@node0 tmp]# cat test.sh

#!/bin/sh

set -x

a='abc'

set +x

echo '123'

[root@node0 tmp]# sh test.sh

+ a=abc

+ set +x

123

posted @ 2020-06-08 22:08  jeancheng  阅读(153)  评论(0编辑  收藏  举报