<title>A simple shell script</title> A simple shell script to write
Suppose I want to know how many people are currently logged on the system, and use the who
command to tell you who is logged in to the system now:
1.[[email protected] ~]$ who
2.KANO tty1 2016-02-1501:47 (:0)
3.KANO pts/0 2016-02-1501:48 (kelvin)
Of course on the PC, the list listed may be only as short as it is. However, on some large, multi-user systems, the list listed can be very long. At this point we can use the total number of users to automatically calculate. wc
is a word count program that calculates the number of travel (line), Word, and number of characters (character).
We used wc -l
to calculate the number of trips, indicating the number of users logged in
1.[KANO@kelvin ~]$ who|wc -l
2.2
Next, we turn this pipeline into a separate command.
1.[KANO@kelvin~]$ Cat>nusers#建立文件, use the input from the Cat replication terminal
2.Who|wc-l#程序内容
3.^D #ctrl + D indicates end-of-file
4.[KANO@kelvin~]$ chmod +x Nusers#让文件拥有执行的权限
5.[KANO@kelvin~]$ ./nusers#执行测试
6.2 #输出结果
A typical representative development cycle for a miniaturized shell script:
- Test directly on the command line
- Find the proper syntax to get the job done, put them in a separate script, and set execution permissions
- Use the script directly
Perfect
Our nusers shell script is not a compiled program, so when the shell asks the kernel to execute it, the kernel will error "Executable format file" (not an executable). When the shell receives this error message, a new/bin/bash copy is started to execute the program. When the system has only one shell, the fallback mechanism is very convenient. But in general our system will have several shells, so we need to #!
tell the kernel which shell to execute the specified shell script with the first line of the script file.
1.[KANO@kelvin
2.#! /bin/bash -
3.
4.who|wc -l
The option--which means there is no shell option--is based on security considerations and avoids some degree of deceptive attack (spoofing attack).
A simple shell script