- Ubuntu 20.04 Essentials
- Neil Smyth
- 389字
- 2021-06-11 17:39:43
9.13 Writing Shell Scripts
So far we have focused exclusively on the interactive nature of the Bash shell. By interactive we mean manually entering commands at the prompt one by one and executing them. In fact, this is only a small part of what the shell is capable of. Arguably one of the most powerful aspects of the shell involves the ability to create shell scripts. Shell scripts are essentially text files containing sequences of statements that can be executed within the shell environment to perform tasks. In addition to the ability to execute commands, the shell provides many of the programming constructs such as for and do loops and if statements that you might reasonably expect to find in a scripting language.
Unfortunately a detailed overview of shell scripting is beyond the scope of this chapter. There are, however, many books and web resources dedicated to shell scripting that do the subject much more justice than we could ever hope to achieve here. In this section, therefore, we will only be providing a very small taste of shell scripting.
The first step in creating a shell script is to create a file (for the purposes of this example we will name it simple.sh) and add the following as the first line:
#!/bin/sh
The #! is called the “shebang” and is a special sequence of characters indicating that the path to the interpreter needed to execute the script is the next item on the line (in this case the sh executable located in /bin). This could equally be, for example, /bin/csh or /bin/ksh if either were the interpreter you wanted to use.
The next step is to write a simple script:
#!/bin/sh
for i in *
do
echo $i
done
All this script does is iterate through all the files in the current directory and display the name of each file. This may be executed by passing the name of the script through as an argument to sh:
$ sh simple.sh
In order to make the file executable (thereby negating the need to pass it through to the sh command) the chmod command can be used:
$ chmod +x simple.sh
Once the execute bit has been set on the file’s permissions, it may be executed directly. For example:
$ ./simple.sh
- Word 2000、Excel 2000、PowerPoint 2000上機(jī)指導(dǎo)與練習(xí)
- ETL with Azure Cookbook
- 反饋系統(tǒng):多學(xué)科視角(原書第2版)
- 教父母學(xué)會(huì)上網(wǎng)
- 大學(xué)計(jì)算機(jī)應(yīng)用基礎(chǔ)
- RPA(機(jī)器人流程自動(dòng)化)快速入門:基于Blue Prism
- 基于ARM 32位高速嵌入式微控制器
- 從零開始學(xué)SQL Server
- HBase Essentials
- 企業(yè)級(jí)Web開發(fā)實(shí)戰(zhàn)
- Generative Adversarial Networks Projects
- x86/x64體系探索及編程
- 從實(shí)踐中學(xué)嵌入式Linux操作系統(tǒng)
- Ubuntu 9 Linux應(yīng)用基礎(chǔ)
- Hands/On Kubernetes on Azure