- 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
- 大數據技術與應用基礎
- 大學計算機基礎:基礎理論篇
- Visual Basic從初學到精通
- 樂高創意機器人教程(中級 下冊 10~16歲) (青少年iCAN+創新創意實踐指導叢書)
- INSTANT Varnish Cache How-to
- Python Data Science Essentials
- 水晶石精粹:3ds max & ZBrush三維數字靜幀藝術
- Learning C for Arduino
- Salesforce Advanced Administrator Certification Guide
- 自動化生產線安裝與調試(三菱FX系列)(第二版)
- 從零開始學Java Web開發
- Visual Studio 2010 (C#) Windows數據庫項目開發
- 經典Java EE企業應用實戰
- INSTANT Adobe Story Starter
- Photoshop CS4數碼攝影處理50例