Linux shell脚本用法(linux教程:shell脚本中如何使用函数)

运行 Shell 脚本有两种方法:

1、作为可执行程序

创建脚本test.sh,内容如下:

#!/bin/bash

echo "Hello World !"

将上面的代码保存为 test.sh,并 cd 到相应目录:

chmod u+x ./test.sh #使脚本具有执行权限

./test.sh #执行脚本

注意:

一定要写成 ./test.sh,而不是 test.sh,如果是直接写test.sh,linux 系统会去 PATH 里寻找有没有名字是test.sh 的,你的当前目录通常不在 PATH 里,所以写成 test.sh,要用 ./test.sh 告诉系统说,就在当前目录找。


2、作为解释器参数

这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如:

/bin/sh test.sh

Shell 包含引用外部脚本,方便封装一些公用的代码

Shell 文件包含的语法格式如下:

方法1:

. filename # 注意点号(.)和文件名中间有一个空格

方法2:

source filename

代码举例

创建两个 shell 脚本文件。

test1.sh 代码如下:

#!/bin/bash

name="everyone"


test2.sh 代码如下:

#!/bin/bash

#使用 . 号来引用test1.sh 文件

. ./test1.sh

# 或者使用以下包含文件代码

# source ./test1.sh

echo "hello $name"


给test2.sh 添加可执行权限并执行

$ chmod +x test2.sh

$ ./test2.sh

hello everyone

原文链接:,转发请注明来源!