如何入门 Linux Shell 脚本编写
脚本
![](/data/attachment/album/202305/19/235745hz7r48umu1eerm2e.jpg)



> 
> 各位读者，我们将在本文中介绍如何在 Linux 或 UNIX 系统中入门 Shell 脚本编写。
> 
> 
> 


### 什么是 Shell 呢？


Shell（交互界面）是类 UNIX/Linux 操作系统中的一个解释器。它将用户输入的命令解释成操作系统的系统调用来执行这些命令。简单来说，Shell 形式上是操作系统的包装。比如，你可能使用 Shell 命令来列出目录中的文件，如 [ls](https://www.linuxtechi.com/linux-ls-command-examples-beginners/) 命令，或使用命令复制，如 `cp` 命令。



```
$ ls
Desktop Documents Downloads Music Pictures playbook.yaml Public snap Templates test5 Videos

```

在上方的例子中，当你输入 `ls` 并按下回车键。`$` 符号是 Shell 的提示符，意味着 Shell 等着命令的输入。下面的一行就是当前目录下的文件名。


### 什么是 Shell 提示符？


提示符，即 `$`，被称作命令提示符，是由 Shell 发出的（LCTT 译注：这个概念，可能有误。请参看：<https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Controlling-the-Prompt> ）。当提示符出现后（LCTT 译注：此处提示符并不特指 `$` 符号），你就可以输入命令了。Shell 将会在你按下回车键后读取你的输入。它会通过查看你输入的第一个单词来确定你希望执行的命令。“单词”指的是一组连续的字符。空格和制表符作为分割单词的标志。


### 不同类型的 Shell


由于没有限制只能有一个 Shell，你可以按照自己的意愿来自由选择运行任何一种 Shell。这当然挺好的，但是在不清楚其它替代方案的情况下选择一种 Shell 没有多大益处。下面列出了一些 UNIx/Linux 下常见的 Shell。


#### Sh（Bourne Shell）


最初的 Unix Shell 通常被称作 Sh，是 Shell（或 Bourne Shell）的简写，以其作者 Steven Bourne 命名。它在几乎所有的类 UNIX 操作系统下都可以找到。基本的 Bourne Shell 仅支持相当有限的命令行编辑。你可以输入字符，使用退格键删除字符，还有就是按下回车键来执行命令。当命令行出现异常了，你可以按下 `Ctrl-C` 组合键来终止整个命令。


#### Csh（C Shell）


它是由加利福尼亚大学伯克利分校的 Bill Joy 设计的，由于它的语法和 C 语言相似，所以被命名为 C Shell。这种 Shell 在 Bourne shell 的基础上增加了一些实用功能，尤其是可以重用之前的命令来帮助创建之后要执行的命令。当你去完成一项专门任务的时候，大多数的情况下需要执行不止一条命令，这样 C shell 的能力就相当有用了。


#### Ksh（Korn Shell）


它是由贝尔实验室的 David Korn 创造的，Korn Shell 提供了和 C Shell 相同的增强，其中有一项重要的不同：Korn Shell 提供了对旧的 Bourne Shell 语法的向后兼容。在 Unix 下，如 AIX & HP-UX 上，Korn Shell 是默认 Shell。


#### Bash（Bourne Again Shell）


Bash 提供了像 Korn Shell 一样的命令行编辑，像 C Shell 一样的文件名补全和许多其它的高级功能。许多用户认为 Bash 集 Korn Shell 和 C Shell 的优点于一身。在 Linux 和 Mac OS X 系统下，Bash 是默认的 Shell。


#### Tcsh（T C Shell）


Linux 系统推广了 Tcsh。Tcsh 扩展了传统的 csh，增加了命令行编辑、文件名补全和其它功能。例如，当你按下 `Tab` 键后，Tcsh 会补全文件和目录名（与 Bash 中的按键相同）。旧的 C Shell 不支持这项功能。


### 什么是 Shell 脚本呢？


Shell 脚本是包含一条或多条命令的文本文件。在 Shell 脚本中，Shell 程序假定文本文件的每一行是一条不同的命令。这些命令的大部分就和你在 Shell 窗口手动输入的一样。


#### 为什么要使用 Shell 脚本呢？


Shell 脚本被用来自动化管理任务、简化复杂的配置细节，并且充分运用操作系统的性能。有了组合不同命令的能力就可以创造新命令了，从而增加操作系统的价值。此外，结合使用 Shell 与图形化桌面环境，可以兼得二者之长。


从系统管理员的角度看，日复一日的重复工作可以使用 Shell 脚本来实现自动处理，那就可以节约时间从事其它高质量的工作。


### 创建第一个 Shell 脚本


在当前工作目录下创建一个名为 `myscript.sh` 的文本文件，所有的 Shell 脚本都有 `.sh` 的扩展名（LCTT 译注：Linux 下根本没有扩展名一说，没有这个扩展一样是可以执行的）。脚本的第一行是 `#!/bin/sh` 或 `#!/bin/bash`，因为 `#` 符号被称作 “hash” 并且 `!` 符号被称作 “bang” 故被称为 shebang（释伴）。至于 `/bin/sh` 和 `/bin/bash` 则指出了命令将被 Sh 还是 Bash shell 执行。


以下就是 `myscript.sh` 的内容：



```
#!/bin/bash
# Written by LinuxTechi
echo
echo "Current Working Directory: $(pwd)"
echo
echo "Today' Date & Time: $(date)"
DISK=$(df -Th)
echo
echo "Disk Space on System:"
echo "$DISK"

```

上方的脚本将会展示当前工作目录、今天的日期与时间，还有磁盘空间。我们需要用到 [echo 命令](https://www.linuxtechi.com/echo-command-examples-in-linux/) 和其它 [Linux 命令](https://www.linuxtechi.com/20-linux-commands-interview-questions-answers/) 来实现这个脚本。


使用如下的 [chmod 命令](https://www.linuxtechi.com/chmod-command-examples-in-linux/) 来给文件增加执行权限：



```
$ chmod a+x myscript.sh

```

现在来执行脚本：



```
$ sh myscript.sh
或
$ ./myscript.sh

```

注意：在当前目录下执行当前目录下的 Shell 脚本，须使用 `./<脚本名>` 方式，如下所示：


![](/data/attachment/album/202305/19/235953e44jzssz4iqf1wyy.jpg)


#### 在 Shell 脚本中获取用户输入


`read` 命令用来获取用户的键盘输入，并且将之赋值给一个变量。`echo` 命令用来展示内容。


让我们更改上方的脚本以使之获取输入：



```
#!/bin/bash
# Written by LinuxTechi
read -p "Your Name: " NAME
echo
echo "Today' Date & Time: $(date)"
echo
read -p "Enter the file system:" DISK
echo "$(df -Th $DISK)""

```

现在，再执行脚本试试，这回应该会有输入信息的提醒：



```
$ ./myscript.sh
Your Name: Pradeep Kumar

Today' Date & Time: Sat 15 Oct 05:32:38 BST 2022

Enter the file system:/mnt/data
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/volgrp01-lv01 ext4 14G 24K 13G 1% /mnt/data

```

![](/data/attachment/album/202305/20/000008gvifoiiy9pspgwww.jpg)


完美，上方的输出表明脚本有输入提醒，并加工处理了相应的数据。


本文结束。希望对你是有用的。非常欢迎任何的疑问、反馈。


*（题图：MJ/f83b771e-a70d-4c62-a169-ec42e9004a14）*




---


via: <https://www.linuxtechi.com/get-started-shell-scripting-linux/>


作者：[Pradeep Kumar](https://www.linuxtechi.com/author/pradeep/) 选题：[lkxed](https://github.com/lkxed) 译者：[cyberwaddle](https://github.com/cyberwaddle) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Hello readers, In this post, we will cover how to get started with shell scripting in Linux or UNIX systems.

#### What is a Shell?

A shell is an interpreter in UNIX/Linux like operating systems. It takes commands typed by the user and calls the operating system to run those commands. In simple terms a shell acts as form of wrapper around the OS. For example , you may use the shell to enter a command to list the files in a directory , such as [ls command](https://www.linuxtechi.com/linux-ls-command-examples-beginners/) , or a command to copy ,such as cp.

$ ls Desktop Documents Downloads Music Pictures playbook.yaml Public snap Templates test5 Videos $

In this example , when you simply type ls and press enter . The $ is the shell prompt , which tells you the the shell awaits your commands.The remaining lines are the names of the files in the current directory.

#### What is Shell Prompt?

The prompt, $, which is called command prompt, is issued by the shell. While the prompt is displayed, you can type a command. The shell reads your input after you press Enter. It determines the command you want executed by looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs separate words.

## What are different types of Shells


since there is no monopoly of shells , you are free to run any shell as you wish. That’s all well and good , but choosing a shell without knowing the alternative is not very helpful. Below are lists of shells available in UNIX/Linux.

#### The Bourne Shell

The Original Unix Shell is known as sh , short for shell or the Bourne shell , named for steven Bourne , the creator of sh. This is available on almost all the UNIX like operating system. The Basic bourne shell supports only the most limited command line editing, You can type the Characters,remove characters one at a time with the Backspace key and Press enter to execute the command. If command line gets messed up , you can press Ctrl-C to cancel the whole command.

#### The C Shell

It is desgined by Bill Joy at the university of california at Berkeley , the C shell was so named because much of its syntax parallels that of C programming language. This shell adds some neat features to the Bourne shell,especially the ability to recall previous commands to help create future commands.Because it is very likely you will need to execute more than one command to perform a particular task,this C shell capability is very useful.

#### The Korn Shell

It is created by David Korn at AT&T Bell laboratories , the korn shell or ksh offers the same kind of enhancements offers by the C Shell , with one important difference: The korn shell is backward compatible with the older Bourne shell Synatx. In UNIX like AIX & HP-UX korn shell is the default shell.

#### Bash (The Bourne Again Shell)

Bash offers command-line editing like the korn shell,file name completion like the C shell and a lot of other advance features. Many Users view bash as having the best of the Korn and C shells in one shell. In Linux and Mac OS X system , bash is the default shell.

#### tcsh ( The T C Shell)

Linux systems popularized the T C shell ot Tcsh. Tcsh extends the traditional csh to add command line editing,file name completion and more. For example , tcsh will complete the file and directory names when you press Tab key(the same key used in bash). The older C shell did not support this feature.

## What is a Shell Script?


A Shell Script is a text file that contains one or more commands. In a shell script, the shell assumes each line of text file holds a separate command. These Commands appear for most parts as if you have typed them in at a shell windows.

#### Why to use Shell Script ?


Shell scripts are used to automate administrative tasks,encapsulate complex configuration details and get at the full power of the operating system.The ability to combine commands allows you to create new commands ,thereby adding value to your operating system.Furthermore ,combining a shell with graphical desktop environment allows you to get the best of both worlds.

In Linux system admin profile, day to day repeated tasks can be automated using shell script which saves time and allow admins to work on quality work.

#### Creating first shell script


Create a text file in your current working directory with a name myscript.sh , all the shell scripts have an “.sh” extension. First line of a shell script is either #!/bin/sh or #!/bin/bash , it is known as shebang because # symbol is called hash and ! Symbol is called a bang. Where as /bin/sh & /bin/bash shows that commands to be executed either sh or bash shell.

Below are the content of myscript.sh

#!/bin/bash # Written by LinuxTechi echo echo "Current Working Directory: $(pwd)" echo echo "Today' Date & Time: $(date)" DISK=$(df -Th) echo echo "Disk Space on System:" echo "$DISK"

Above shell script will display the current working , today’s date & time along with file system disk space. We have used [echo command](https://www.linuxtechi.com/echo-command-examples-in-linux/) and other [linux commands](https://www.linuxtechi.com/20-linux-commands-interview-questions-answers/) to build this script.

Assign the executable permissions using below [chmod command](https://www.linuxtechi.com/chmod-command-examples-in-linux/)

$ chmod a+x myscript.sh

Now execute the script.

$ sh myscript.sh or $ ./myscript.sh

Note: To execute any shell script available in current directory, use ./<script-name> as shown below,

output,

#### Taking Input from the user in shell script

Read command is used to take inputs from user via keyboard and assign the value to a variable. echo command is used to display the contents.

Let’s modify above script so that it starts taking input,

#!/bin/bash # Written by LinuxTechi read -p "Your Name: " NAME echo echo "Today' Date & Time: $(date)" echo read -p "Enter the file system:" DISK echo "$(df -Th $DISK)"

Now, try to execute the script this time it should prompt to enter details.

$ ./myscript.sh Your Name: Pradeep Kumar Today' Date & Time: Sat 15 Oct 05:32:38 BST 2022 Enter the file system:/mnt/data Filesystem Type Size Used Avail Use% Mounted on /dev/mapper/volgrp01-lv01 ext4 14G 24K 13G 1% /mnt/data $

Perfect, above output confirms that scripting is prompting for input and processing data.

That’s conclude the post. I hope you have found it informative. Kindly do post your queries and feedback in below comments section.

Read Also: [How to Debug a Bash Shell Script in Linux](https://www.linuxtechi.com/debugging-shell-scripts-in-linux/)