加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 服务器 > 搭建环境 > Windows > 正文

怎样用Bash编程:语法和工具

发布时间:2019-11-09 10:26:58 所属栏目:Windows 来源:David Both
导读:让我们通过本系列文章来学习基本的 Bash 编程语法和工具,以及如何使用变量和控制运算符,这是三篇中的第一篇。 Shell 是操作系统的命令解释器,其中 Bash 是我最喜欢的。每当用户或者系统管理员将命令输入系统的时候,Linux 的 shell 解释器就会把这些命

当一段程序的返回码大于零时,使用 || 运算符可以让你在后面接着执行另一段程序。简单语法如下:

  1. command1 || command2

解读一下,“假如 command1 失败,执行 command2”。隐藏的逻辑是,如果 command1 成功,跳过 command2。下面实践一下,仍然是创建新目录:

  1. [student@studentvm1 ~]$ Dir=/root/testdir ; mkdir $Dir || echo "$Dir was not created."
  2. mkdir: cannot create directory '/root/testdir': Permission denied
  3. /root/testdir was not created.
  4. [student@studentvm1 ~]$

正如预期,因为目录无法创建,第一条命令失败了,于是第二条命令被执行。

&&|| 两种运算符结合起来才能发挥它们的最大功效。请看下面例子中的流程控制方法:

  1. 前置 commands ; command1 && command2 || command3 ; 跟随 commands

语法解释:“假如 command1 退出时返回码为零,就执行 command2,否则执行 command3。”用具体代码试试:

  1. [student@studentvm1 ~]$ Dir=/root/testdir ; mkdir $Dir && cd $Dir || echo "$Dir was not created."
  2. mkdir: cannot create directory '/root/testdir': Permission denied
  3. /root/testdir was not created.
  4. [student@studentvm1 ~]$

现在我们再试一次,用你的家目录替换 /root 目录,你将会有权限创建这个目录了:

  1. [student@studentvm1 ~]$ Dir=~/testdir ; mkdir $Dir && cd $Dir || echo "$Dir was not created."
  2. [student@studentvm1 testdir]$

command1 && command2 这样的控制语句能够运行的原因是,每条命令执行完毕时都会给 shell 发送一个返回码,用来表示它执行成功与否。默认情况下,返回码为 0 表示成功,其他任何正值表示失败。一些系统管理员使用的工具用值为 1 的返回码来表示失败,但其他很多程序使用别的数字来表示失败。

Bash 的内置变量 $? 可以显示上一条命令的返回码,可以在脚本或者命令行中非常方便地检查它。要查看返回码,让我们从运行一条简单的命令开始,返回码的结果总是上一条命令给出的。

  1. [student@studentvm1 testdir]$ ll ; echo "RC = $?"
  2. total 1264
  3. drwxrwxr-x 2 student student 4096 Mar 2 08:21 chapter25
  4. drwxrwxr-x 2 student student 4096 Mar 21 15:27 chapter26
  5. -rwxr-xr-x 1 student student 92 Mar 20 15:53 TestFile1
  6. drwxrwxr-x. 2 student student 663552 Feb 21 14:12 testdir
  7. drwxr-xr-x. 2 student student 4096 Dec 22 13:15 Videos
  8. RC = 0
  9. [student@studentvm1 testdir]$

在这个例子中,返回码为零,意味着命令执行成功了。现在对 root 的家目录测试一下,你应该没有权限:

  1. [student@studentvm1 testdir]$ ll /root ; echo "RC = $?"
  2. ls: cannot open directory '/root': Permission denied
  3. RC = 2
  4. [student@studentvm1 testdir]$

本例中返回码是 2,表明非 root 用户没有权限进入这个目录。你可以利用这些返回码,用控制运算符来改变程序执行的顺序。

总结

本文将 Bash 看作一门编程语言,并从这个视角介绍了它的简单语法和基础工具。我们学习了如何将数据输出到 STDOUT,怎样使用变量和控制运算符。在本系列的下一篇文章中,将会重点介绍能够控制指令执行流程的逻辑运算符。

【编辑推荐】

  1. 一篇文章讲清Linux操作系统的目录结构
  2. 在Linux上用strace来理解系统调用
  3. 推荐4款Linux系统漏洞扫描、评估工具
  4. 在Linux中加速工作的键盘快捷键
  5. 初级:如何更新Fedora Linux系统
【责任编辑:庞桂玉 TEL:(010)68476606】
点赞 0

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读