一、exit命令

exit命令用来退出当前shell进程,并返回一个退出状态;使用$?可以接收这个退出状态。

exit命令可以接受一个整数值作为参数,代表退出状态。如果不指定,默认状态值是 0。

exit退出状态只能是一个介于 0~255 之间的整数,其中只有 0 表示成功,其它值都表示失败。

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

#! /bin/bash

if [ $# -ne 1 ]  # 如果传入参数个数等于1,则正常退出;否则非正常退出。
then
    echo "arguments not valid"
    exit 1
else
    echo "arguments valid"
    exit 0
fi

执行该脚本:
acs@9e0ebfcd82d7:~$ chmod +x test.sh
acs@9e0ebfcd82d7:~$ ./test.sh acwing
arguments valid
acs@9e0ebfcd82d7:~$ echo $?  # 传入一个参数,则正常退出,exit code为0
0
acs@9e0ebfcd82d7:~$ ./test.sh
arguments not valid
acs@9e0ebfcd82d7:~$ echo $?  # 传入参数个数不是1,则非正常退出,exit code为1
1

二、文件重定向

1、每个进程默认打开3个文件描述符:

    stdin标准输入,从命令行读取数据,文件描述符为0
    stdout标准输出,向命令行输出数据,文件描述符为1
    stderr标准错误输出,向命令行输出数据,文件描述符为2

可以用文件重定向将这三个文件重定向到其他文件中。

2、重定向命令列表
命令                                  说明
command > file     将stdout重定向到file中
command < file     将stdin重定向到file中
command >> file     将stdout以追加方式重定向到file中
command n> file     将文件描述符n重定向到file中
command n>> file     将文件描述符n以追加方式重定向到file中

3、输入和输出重定向
echo -e "Hello \c" > output.txt  # 将stdout重定向到output.txt中
echo "World" >> output.txt  # 将字符串追加到output.txt中

read str < output.txt  # 从output.txt中读取字符串

echo $str  # 输出结果:Hello World

同时重定向stdin和stdout

创建bash脚本:

#! /bin/bash

read a
read b

echo $(expr "$a" + "$b")

创建input.txt,里面的内容为:

3
4

执行命令:
acs@9e0ebfcd82d7:~$ chmod +x test.sh  # 添加可执行权限
acs@9e0ebfcd82d7:~$ ./test.sh < input.txt > output.txt  # 从input.txt中读取内容,将输出写入output.txt中
acs@9e0ebfcd82d7:~$ cat output.txt  # 查看output.txt中的内容
7

三、引入外部脚本

类似于C/C++中的include操作,bash也可以引入其他文件中的代码。

语法格式:
. filename  # 注意点和文件名之间有一个空格


source filename

示例
创建test1.sh,内容为:

#! /bin/bash

name=yxc  # 定义变量name

然后创建test2.sh,内容为:

#! /bin/bash

source test1.sh # 或 . test1.sh

echo My name is: $name  # 可以使用test1.sh中的变量

执行命令:
acs@9e0ebfcd82d7:~$ chmod +x test2.sh
acs@9e0ebfcd82d7:~$ ./test2.sh
My name is: yxc

最新文章

  1. myBatis foreach详解【转】
  2. 初识reactJs 相关
  3. 2.5 ListView
  4. ntp.conf:很少有人提及的事
  5. List集合
  6. OpenSessionInViewFilter与org.springframework.dao.InvalidDataAccessApiUsageException
  7. &quot;类名.this&quot;与&quot;this&quot;的区别
  8. [Swust OJ 249]--凸包面积
  9. Linux命令: ln
  10. 设计模式(三)建造者模式Builder(创建型)
  11. 痞子衡随笔:常用的数据传输差错检测技术(1)- 奇偶校验(Parity Check)
  12. TopCoder SRM 561 Div 1 - Problem 1000 Orienteering
  13. Java设计模式之《适配器模式》及应用场景
  14. [Swift]LeetCode222. 完全二叉树的节点个数 | Count Complete Tree Nodes
  15. IPFS 使用入门
  16. If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
  17. nginx安装配置: configure命令
  18. Python之保存和读取字典
  19. Android性能优化系列之App启动优化
  20. PHP文本式留言板——php经典实例

热门文章

  1. Vue34 VueX
  2. 最大K段和
  3. 【CTO变形记】整体系统思维-从现象到本质
  4. CF1250C Trip to Saint Petersburg
  5. MySQL数据类型补充
  6. KB 与 KiB
  7. Cesium渲染调度
  8. 基于Python的OpenGL 03 之纹理
  9. linux系统安装MySQL服务,详细图文教程
  10. AD域安装后无法打开网络适配器,提示无法访问指定设备,路径或文件,你可能没有。。。