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

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

主站蜘蛛池模板: 嘉义市| 宽城| 麦盖提县| 武山县| 黔西| 城固县| 应城市| 康马县| 大同市| 博野县| 安龙县| 柳州市| 六枝特区| 白朗县| 筠连县| 东明县| 汾西县| 民和| 武宣县| 陆河县| 城固县| 平武县| 紫金县| 濉溪县| 达州市| 大竹县| 蒙山县| 虎林市| 芦山县| 汝州市| 永川市| 县级市| 留坝县| 灵璧县| 普格县| 贞丰县| 察隅县| 三门县| 绥中县| 铜川市| 图们市|