官术网_书友最值得收藏!

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

主站蜘蛛池模板: 凤台县| 弥勒县| 西乌珠穆沁旗| 海城市| 绩溪县| 江安县| 安岳县| 湄潭县| 临潭县| 秦安县| 长武县| 正宁县| 吴堡县| 吴堡县| 乃东县| 武威市| 安顺市| 东莞市| 察隅县| 建始县| 盘山县| 平利县| 栖霞市| 哈巴河县| 噶尔县| 永康市| 温宿县| 宜城市| 辽宁省| 美姑县| 启东市| 黎平县| 廊坊市| 应城市| 许昌县| 凯里市| 固安县| 绥棱县| 元谋县| 泾源县| 乌鲁木齐县|