shell入门第三讲

1、写简单的shell脚本

1.1、打印hello world

打印hello world我想大家在接触高级编程语言是最先学会的,当然我们的shell并不属于编程语言,它只是一种解释性的脚本语言。我们先来看看第一个脚本语言。

[root@localhost ~]# vim hello.sh

#!/bin/bash

echo “hello world”

所谓shebang其实就是在很多脚本的第一行出现的以”#!”开头的注释,他指明了当我们没有指定解释器的时候默认的解释器,一般可能是下面这样:

bash

#!/bin/bash

因为我们一般都使用bash shell,因此其他的shell类型不常用,因此我们只写这个就行。

当然,上面的这种写法可能不太具备适应性,毕竟脚本也有使用不同发行版系统的平台限制,一般我们会用下面的方式来指定:

#!/usr/bin/env bash

像这种的是我们比较推荐的使用方式。

第二行的echo命令表示打印字串,要打印什么内容就在echo命令后面写上就可以了。要打印的内容建议使用上双引号,当然单引号也是可以的,不过两者在使用上有一些小区别,后面我们会给大家解释。

1.2、执行shell脚本

执行shell脚本大概有这几种方法:

1.2.1、直接用bash解释器执行

[root@localhost ~]# bash hello.sh

hello world

像上面这种hello.sh脚本不带有x执行权限使用bash命令就可以执行此脚本

1.2.2、使用 ./ 来执行

默认我们编写的shell脚本是不带x执行权限的,那么就不能执行,比如:

[root@localhost ~]# ls -l hello.sh

-rw-r–r– 1 root root 31 Mar 18 09:26 hello.sh

此时执行看看

[root@localhost ~]# ./hello.sh

-bash: ./hello.sh: Permission denied

因为没有赋予x权限,因此就不能使用 ./ 的方式来执行它。

此时我们添加x权限,来执行

[root@localhost ~]# chmod u+x hello.sh

[root@localhost ~]# ls -l hello.sh

-rwxr–r– 1 root root 31 Mar 18 09:26 hello.sh

[root@localhost ~]# ./hello.sh

hello world

这样子就可以执行了。

1.2.3、使用source命令来执行

使用source命令也可以不赋予x权限就可以执行,比如:

[root@localhost ~]# ls -l hello.sh

-rw-r–r– 1 root root 31 Mar 18 09:40 hello.sh

[root@localhost ~]# source hello.sh

hello world

1.2.4、使用 .  hello.sh 来执行

[root@localhost ~]# ls -l hello.sh

-rw-r–r– 1 root root 31 Mar 18 09:40 hello.sh

[root@localhost ~]# . hello.sh

hello world

前两种方式使用的人比较多。后两种对我们来说也要学习会

好了,这就是今天分享的执行shell脚本的集中方式,希望大家能够吸收。

声明:文章来源于网络,如有侵权请联系删除!

相关新闻

历经多年发展,已成为国内好评如潮的Linux云计算运维、SRE、Devops、网络安全、云原生、Go、Python开发专业人才培训机构!