Unix 简明教程
Unix - Getting Started
What is Unix ?
Unix 操作系统是一组程序,充当计算机与用户之间的链接。
The Unix operating system is a set of programs that act as a link between the computer and the user.
在计算机内部分配系统资源和协调所有详细信息的计算机程序称为 operating system 或 kernel 。
The computer programs that allocate the system resources and coordinate all the details of the computer’s internals is called the operating system or the kernel.
用户通过称为 shell 的程序与内核通信。shell 是一个命令行解释器;它翻译用户输入的命令,并将它们转换为内核可以理解的语言。
Users communicate with the kernel through a program known as the shell. The shell is a command line interpreter; it translates commands entered by the user and converts them into a language that is understood by the kernel.
-
Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs.
-
There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are a few examples. Linux is also a flavor of Unix which is freely available.
-
Several people can use a Unix computer at the same time; hence Unix is called a multiuser system.
-
A user can also run multiple programs at the same time; hence Unix is a multitasking environment.
Unix Architecture
以下是 Unix 系统的基本框图−
Here is a basic block diagram of a Unix system −

将所有 Unix 版本联合起来的主要概念是以下四个基本概念−
The main concept that unites all the versions of Unix is the following four basics −
-
Kernel − The kernel is the heart of the operating system. It interacts with the hardware and most of the tasks like memory management, task scheduling and file management.
-
Shell − The shell is the utility that processes your requests. When you type in a command at your terminal, the shell interprets the command and calls the program that you want. The shell uses standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are the most famous shells which are available with most of the Unix variants.
-
Commands and Utilities − There are various commands and utilities which you can make use of in your day to day activities. cp, mv, cat and grep, etc. are few examples of commands and utilities. There are over 250 standard commands plus numerous others provided through 3rd party software. All the commands come along with various options.
-
Files and Directories − All the data of Unix is organized into files. All files are then organized into directories. These directories are further organized into a tree-like structure called the filesystem.
System Bootup
如果您有一台安装了 Unix 操作系统的计算机,那么您只需要打开系统即可使其启动。
If you have a computer which has the Unix operating system installed in it, then you simply need to turn on the system to make it live.
一旦您打开系统,它将开始启动,最后提示您登录系统,这是一项登录系统并将其用于您的日常活动的活动。
As soon as you turn on the system, it starts booting up and finally it prompts you to log into the system, which is an activity to log into the system and use it for your day-to-day activities.
Login Unix
当您首次连接到 Unix 系统时,通常会看到如下提示−
When you first connect to a Unix system, you usually see a prompt such as the following −
login:
To log in
-
Have your userid (user identification) and password ready. Contact your system administrator if you don’t have these yet.
-
Type your userid at the login prompt, then press ENTER. Your userid is case-sensitive, so be sure you type it exactly as your system administrator has instructed.
-
Type your password at the password prompt, then press ENTER. Your password is also case-sensitive.
-
If you provide the correct userid and password, then you will be allowed to enter into the system. Read the information and messages that comes up on the screen, which is as follows.
login : amrood
amrood's password:
Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
$
将为您提供一个命令提示符(有时称为 $ 提示符),您可以在其中键入所有命令。例如,要查看日历,您需要按如下方式键入 cal 命令−
You will be provided with a command prompt (sometime called the $ prompt ) where you type all your commands. For example, to check calendar, you need to type the cal command as follows −
$ cal
June 2009
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
$
Change Password
所有 Unix 系统都需要密码,以帮助确保您的文件和数据仍然是您的文件和数据,并且系统本身可以抵御黑客和破解者。以下是更改密码的步骤−
All Unix systems require passwords to help ensure that your files and data remain your own and that the system itself is secure from hackers and crackers. Following are the steps to change your password −
Step 1 − 首先,在命令提示符下键入密码,如下所示。
Step 1 − To start, type password at the command prompt as shown below.
Step 2 - 输入您的旧密码,即您当前正在使用的密码。
Step 2 − Enter your old password, the one you’re currently using.
Step 3 - 输入您的新密码。始终保持密码足够复杂,以便没有人能够猜到它。但确保你能记住它。
Step 3 − Type in your new password. Always keep your password complex enough so that nobody can guess it. But make sure, you remember it.
Step 4 - 您必须通过再次输入密码来验证密码。
Step 4 − You must verify the password by typing it again.
$ passwd
Changing password for amrood
(current) Unix password:******
New UNIX password:*******
Retype new UNIX password:*******
passwd: all authentication tokens updated successfully
$
Note − 我们在这里添加星号 (*) 只是为了表示您需要输入当前密码和新密码的位置,否则在您的系统中。当您键入时,它不会向您显示任何字符。
Note − We have added asterisk (*) here just to show the location where you need to enter the current and new passwords otherwise at your system. It does not show you any character when you type.
Listing Directories and Files
Unix 中的所有数据都组织到文件中。所有文件都组织到目录中。这些目录组织成一个称为文件系统的树形结构。
All data in Unix is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the filesystem.
您可以使用 ls 命令列出目录中可用的所有文件或目录。以下是使用 ls 命令和 -l 选项的示例。
You can use the ls command to list out all the files or directories available in a directory. Following is the example of using ls command with -l option.
$ ls -l
total 19621
drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
-rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php
-rw-rw-r-- 1 amrood amrood 20480 Nov 25 2007 webthumb.tar
-rw-rw-r-- 1 amrood amrood 5654 Aug 9 2007 yourfile.mid
-rw-rw-r-- 1 amrood amrood 166255 Aug 9 2007 yourfile.swf
$
此处以 d….. 开头的条目表示目录。例如,uml、univ 和 urlspedia 是目录,其余条目是文件。
Here entries starting with d….. represent directories. For example, uml, univ and urlspedia are directories and rest of the entries are files.
Who Are You?
当您登录到系统时,您可能想知道: Who am I ?
While you’re logged into the system, you might be willing to know : Who am I?
找出“您是谁”的最简单方法是输入 whoami 命令−
The easiest way to find out "who you are" is to enter the whoami command −
$ whoami
amrood
$
在你的系统上尝试一下。此命令列出了与当前登录关联的账户名称。你也可以尝试 who am i 命令来获取自己的信息。
Try it on your system. This command lists the account name associated with the current login. You can try who am i command as well to get information about yourself.
Who is Logged in?
有时你可能想知道同时登录到电脑的是谁。
Sometime you might be interested to know who is logged in to the computer at the same time.
有三个命令可以让你获取此信息,根据你了解其他用户的程度: users 、 who 和 w 。
There are three commands available to get you this information, based on how much you wish to know about the other users: users, who, and w.
$ users
amrood bablu qadir
$ who
amrood ttyp0 Oct 8 14:10 (limbo)
bablu ttyp2 Oct 4 09:08 (calliope)
qadir ttyp4 Oct 8 12:09 (dent)
$
在你的系统上尝试 w 命令以查看输出。这列出了登录到系统用户的关联信息。
Try the w command on your system to check the output. This lists down information associated with the users logged in the system.
Logging Out
当你结束会话时,你需要退出系统。这样做是为了确保其他人无法访问你的文件。
When you finish your session, you need to log out of the system. This is to ensure that nobody else accesses your files.
To log out
To log out
-
Just type the logout command at the command prompt, and the system will clean up everything and break the connection.
System Shutdown
通过命令行正确关闭 Unix 系统的最一致的方法是使用以下命令之一−
The most consistent way to shut down a Unix system properly via the command line is to use one of the following commands −
Sr.No. |
Command & Description |
1 |
halt Brings the system down immediately |
2 |
init 0 Powers off the system using predefined scripts to synchronize and clean up the system prior to shutting down |
3 |
init 6 Reboots the system by shutting it down completely and then restarting it |
4 |
poweroff Shuts down the system by powering off |
5 |
reboot Reboots the system |
6 |
shutdown Shuts down the system |
您通常需要成为超级用户或 root(Unix 系统上权限最高的用户帐户)才能关闭系统。然而,在一些独立的或个人拥有的 Unix 机箱上,管理用户,有时是普通用户可以这样做。
You typically need to be the super user or root (the most privileged account on a Unix system) to shut down the system. However, on some standalone or personally-owned Unix boxes, an administrative user and sometimes regular users can do so.
Unix - File Management
在本章中,我们将详细讨论 Unix 中的文件管理。Unix 中的所有数据都组织到文件中。所有文件都组织到目录中。这些目录组织成一个称为文件系统的树形结构。
In this chapter, we will discuss in detail about file management in Unix. All data in Unix is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the filesystem.
当您使用 Unix 时,无论哪种方式,您都会花费大量时间使用文件。本教程将帮助您了解如何创建和删除文件、复制和重命名文件、创建指向它们的链接等。
When you work with Unix, one way or another, you spend most of your time working with files. This tutorial will help you understand how to create and remove files, copy and rename them, create links to them, etc.
在 Unix 中,有三种基本类型的文件−
In Unix, there are three basic types of files −
-
Ordinary Files − An ordinary file is a file on the system that contains data, text, or program instructions. In this tutorial, you look at working with ordinary files.
-
Directories − Directories store both special and ordinary files. For users familiar with Windows or Mac OS, Unix directories are equivalent to folders.
-
Special Files − Some special files provide access to hardware such as hard drives, CD-ROM drives, modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and enable you to access a single file using different names.
Listing Files
若要列出存储在当前目录中的文件和目录,请使用以下命令 -
To list the files and directories stored in the current directory, use the following command −
$ls
以下是要在命令中列出示例输出 −
Here is the sample output of the above command −
$ls
bin hosts lib res.03
ch07 hw1 pub test_results
ch07.bak hw2 res.01 users
docs hw3 res.02 work
命令 ls 支持 -l 选项,它将帮助您获取有关已列出文件详细信息 −
The command ls supports the -l option which would help you to get more information about the listed files −
$ls -l
total 1962188
drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
drwxr-xr-x 2 200 300 4096 Nov 25 2007 webthumb-1.01
-rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php
-rw-rw-r-- 1 amrood amrood 20480 Nov 25 2007 webthumb.tar
-rw-rw-r-- 1 amrood amrood 5654 Aug 9 2007 yourfile.mid
-rw-rw-r-- 1 amrood amrood 166255 Aug 9 2007 yourfile.swf
drwxr-xr-x 11 amrood amrood 4096 May 29 2007 zlib-1.2.3
$
以下是所有列出列的信息 −
Here is the information about all the listed columns −
-
First Column − Represents the file type and the permission given on the file. Below is the description of all type of files.
-
Second Column − Represents the number of memory blocks taken by the file or directory.
-
Third Column − Represents the owner of the file. This is the Unix user who created this file.
-
Fourth Column − Represents the group of the owner. Every Unix user will have an associated group.
-
Fifth Column − Represents the file size in bytes.
-
Sixth Column − Represents the date and the time when this file was created or modified for the last time.
-
Seventh Column − Represents the file or the directory name.
在 ls -l 列表示例中,文件行的开头是 d 、 - 或 l 。这些字符表示列出的文件类型。
In the ls -l listing example, every file line begins with a d, -, or l. These characters indicate the type of the file that’s listed.
Sr.No. |
Prefix & Description |
1 |
- Regular file, such as an ASCII text file, binary executable, or hard link. |
2 |
b Block special file. Block input/output device file such as a physical hard drive. |
3 |
c Character special file. Raw input/output device file such as a physical hard drive. |
4 |
d Directory file that contains a listing of other files and directories. |
5 |
l Symbolic link file. Links on any regular file. |
6 |
p Named pipe. A mechanism for interprocess communications. |
7 |
s Socket used for interprocess communication. |
Metacharacters
元字符在 Unix 中具有特殊含义。例如, * and ? are metacharacters. We use * 匹配 0 个或更多字符,一个问号 ( ? ) 匹配单个字符。
Metacharacters have a special meaning in Unix. For example, and ? are metacharacters. We use to match 0 or more characters, a question mark (?) matches with a single character.
例如 −
For Example −
$ls ch*.doc
显示开头字母为 ch 且结尾字母为 .doc 的所有文件 −
Displays all the files, the names of which start with ch and end with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc c
此处, * 用作匹配任何字符的元字符。如果你只想显示所有以 .doc 结尾的文件,则可以使用以下命令 −
Here, * works as meta character which matches with any character. If you want to display all the files ending with just .doc, then you can use the following command −
$ls *.doc
Hidden Files
不可见文件是指其第一个字符是圆点或句点字符 (.) 的文件。Unix 程序(包括 shell)使用这些文件的大多数来存储配置信息。
An invisible file is one, the first character of which is the dot or the period character (.). Unix programs (including the shell) use most of these files to store configuration information.
隐藏文件的一些常见示例包括文件 −
Some common examples of the hidden files include the files −
-
.profile − The Bourne shell ( sh) initialization script
-
.kshrc − The Korn shell ( ksh) initialization script
-
.cshrc − The C shell ( csh) initialization script
-
.rhosts − The remote shell configuration file
若要列出不可见文件,请向 ls 指定 -a 选项 -
To list the invisible files, specify the -a option to ls −
$ ls -a
. .profile docs lib test_results
.. .rhosts hosts pub users
.emacs bin hw1 res.01 work
.exrc ch07 hw2 res.02
.kshrc ch07.bak hw3 res.03
$
-
Single dot (.) − This represents the current directory.
-
Double dot (..) − This represents the parent directory.
Creating Files
您可以使用 vi 编辑器在任何 Unix 系统上创建普通文件。您只需提供以下命令 -
You can use the vi editor to create ordinary files on any Unix system. You simply need to give the following command −
$ vi filename
上述命令将使用给定文件名打开一个文件。现在,按 i 键进入编辑模式。进入编辑模式后,您便可以开始在文件中写入内容,如下面的程序所示 -
The above command will open a file with the given filename. Now, press the key i to come into the edit mode. Once you are in the edit mode, you can start writing your content in the file as in the following program −
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
完成该程序后,按照以下步骤操作:
Once you are done with the program, follow these steps −
-
Press the key esc to come out of the edit mode.
-
Press two keys Shift + ZZ together to come out of the file completely.
您现在将在当前目录中使用@+s10+创建文件。
You will now have a file created with filename in the current directory.
$ vi filename
$
Editing Files
您可以使用@+s11+编辑器编辑现有文件。我们将简要讨论如何打开现有文件:
You can edit an existing file using the vi editor. We will discuss in short how to open an existing file −
$ vi filename
一旦打开文件,您可以按@+s12+键进入编辑模式,然后您可以继续编辑文件。如果您想在文件内四处移动,那么首先您需要按@+s13+键退出编辑模式。此后,您可以使用以下键在文件中移动:
Once the file is opened, you can come in the edit mode by pressing the key i and then you can proceed by editing the file. If you want to move here and there inside a file, then first you need to come out of the edit mode by pressing the key Esc. After this, you can use the following keys to move inside a file −
-
l key to move to the right side.
-
h key to move to the left side.
-
k key to move upside in the file.
-
j key to move downside in the file.
使用上述按键,你可以将光标置于任意位置以进行编辑。定位后,你可以使用 i 键进入编辑模式。完成后,在文件内按 Esc ,最后同时按 Shift + ZZ 两个键以完全退出该文件。
So using the above keys, you can position your cursor wherever you want to edit. Once you are positioned, then you can use the i key to come in the edit mode. Once you are done with the editing in your file, press Esc and finally two keys Shift + ZZ together to come out of the file completely.
Display Content of a File
你可以使用 cat 命令查看文件的内容。以下是一个查看上述创建的文件内容的简单示例:
You can use the cat command to see the content of a file. Following is a simple example to see the content of the above created file −
$ cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
$
你可以使用 -b 选项和 cat 命令一起显示行号,如下所示:
You can display the line numbers by using the -b option along with the cat command as follows −
$ cat -b filename
1 This is unix file....I created it for the first time.....
2 I'm going to save this content in this file.
$
Counting Words in a File
你可以使用 wc 命令获取文件包含的行数、单词数和字符数。以下是一个查看上述创建的文件信息的简单示例:
You can use the wc command to get a count of the total number of lines, words, and characters contained in a file. Following is a simple example to see the information about the file created above −
$ wc filename
2 19 103 filename
$
以下是四个列的详细信息:
Here is the detail of all the four columns −
-
First Column − Represents the total number of lines in the file.
-
Second Column − Represents the total number of words in the file.
-
Third Column − Represents the total number of bytes in the file. This is the actual size of the file.
-
Fourth Column − Represents the file name.
你可以给出多个文件并一次获取这些文件的信息。以下是简单的语法:
You can give multiple files and get information about those files at a time. Following is simple syntax −
$ wc filename1 filename2 filename3
Copying Files
要复制文件,请使用 cp 命令。该命令的基本语法如下:
To make a copy of a file use the cp command. The basic syntax of the command is −
$ cp source_file destination_file
以下是创建 filename 现有文件副本的示例。
Following is the example to create a copy of the existing file filename.
$ cp filename copyfile
$
你现在会在当前目录中找到另一个文件 copyfile 。该文件将与原始文件 filename 完全相同。
You will now find one more file copyfile in your current directory. This file will exactly be the same as the original file filename.
Renaming Files
要更改文件名称,请使用 mv 命令。基本语法如下:
To change the name of a file, use the mv command. Following is the basic syntax −
$ mv old_file new_file
以下程序将现有文件 filename 重命名为 newfile 。
The following program will rename the existing file filename to newfile.
$ mv filename newfile
$
mv 命令将现有文件完全移动到新文件中。在这种情况下,你只会在当前目录中找到 newfile 。
The mv command will move the existing file completely into the new file. In this case, you will find only newfile in your current directory.
Deleting Files
要删除现有文件,请使用 rm 命令。基本语法如下:
To delete an existing file, use the rm command. Following is the basic syntax −
$ rm filename
Caution − 文件可能包含有用的信息。在使用该 Delete 命令时,始终建议谨慎小心。最好将 -i 选项与 rm 命令一起使用。
Caution − A file may contain useful information. It is always recommended to be careful while using this Delete command. It is better to use the -i option along with rm command.
以下示例显示了如何完全删除现有文件 filename 。
Following is the example which shows how to completely remove the existing file filename.
$ rm filename
$
你可以使用以下命令同时删除多个文件:
You can remove multiple files at a time with the command given below −
$ rm filename1 filename2 filename3
$
Standard Unix Streams
在正常情况下,每个 Unix 程序在启动时都会为它打开三个流(文件):
Under normal circumstances, every Unix program has three streams (files) opened for it when it starts up −
-
stdin − This is referred to as the standard input and the associated file descriptor is 0. This is also represented as STDIN. The Unix program will read the default input from STDIN.
-
stdout − This is referred to as the standard output and the associated file descriptor is 1. This is also represented as STDOUT. The Unix program will write the default output at STDOUT
-
stderr − This is referred to as the standard error and the associated file descriptor is 2. This is also represented as STDERR. The Unix program will write all the error messages at STDERR.
Unix - Directory Management
在本章中,我们将详细讨论 Unix 中的目录管理。
In this chapter, we will discuss in detail about directory management in Unix.
目录是一个文件,其唯一任务是存储文件名称及相关信息。所有的文件(普通文件、特殊文件或目录)都包含在目录中。
A directory is a file the solo job of which is to store the file names and the related information. All the files, whether ordinary, special, or directory, are contained in directories.
Unix 使用层次结构来组织文件和目录。该结构通常称为目录树。树有一个根节点斜杠字符 ( / ),所有其他目录都包含在它下面。
Unix uses a hierarchical structure for organizing files and directories. This structure is often referred to as a directory tree. The tree has a single root node, the slash character (/), and all other directories are contained below it.
Home Directory
第一次登录时所在的目录称为你的主目录。
The directory in which you find yourself when you first login is called your home directory.
你将在你的主目录和你创建的子目录中完成大部分工作,以整理你的文件。
You will be doing much of your work in your home directory and subdirectories that you’ll be creating to organize your files.
你可以随时使用以下命令进入你的主目录:
You can go in your home directory anytime using the following command −
$cd ~
$
此处 ~ 表示主目录。假设你必须进入其他用户的目录,请使用以下命令:
Here ~ indicates the home directory. Suppose you have to go in any other user’s home directory, use the following command −
$cd ~username
$
要进入你的上一个目录,可以使用以下命令:
To go in your last directory, you can use the following command −
$cd -
$
Absolute/Relative Pathnames
目录按层次结构排列,根 (/) 在最上面。目录树中任何文件的位置都由其路径名来描述。
Directories are arranged in a hierarchy with root (/) at the top. The position of any file within the hierarchy is described by its pathname.
路径名的元素由 / 分隔。如果路径名是相对于根来描述的,则该路径名是绝对路径名,因此绝对路径名总以 / 开头。
Elements of a pathname are separated by a /. A pathname is absolute, if it is described in relation to root, thus absolute pathnames always begin with a /.
以下是一些绝对文件名示例。
Following are some examples of absolute filenames.
/etc/passwd
/users/sjones/chem/notes
/dev/rdsk/Os3
路径名也可以相对于您的当前工作目录。相对路径名永远不会从 / 开始。相对于用户 amrood 的主目录,一些路径名可能看起来像这样 -
A pathname can also be relative to your current working directory. Relative pathnames never begin with /. Relative to user amrood’s home directory, some pathnames might look like this −
chem/notes
personal/res
要随时确定您在文件系统层次结构中的位置,请输入命令 (cd) 以打印当前工作目录 -
To determine where you are within the filesystem hierarchy at any time, enter the command pwd to print the current working directory −
$pwd
/user0/home/amrood
$
Listing Directories
要列出目录中的文件,可以使用以下语法 -
To list the files in a directory, you can use the following syntax −
$ls dirname
以下是列出 (ls) /usr/local 目录中包含的所有文件的示例 -
Following is the example to list all the files contained in /usr/local directory −
$ls /usr/local
X11 bin gimp jikes sbin
ace doc include lib share
atalk etc info man ami
Creating Directories
我们现在将了解如何创建目录。目录是通过以下命令创建的 -
We will now understand how to create directories. Directories are created by the following command −
$mkdir dirname
此处,directory 是您要创建的目录的绝对或相对路径名。例如,命令 -
Here, directory is the absolute or relative pathname of the directory you want to create. For example, the command −
$mkdir mydir
$
在当前目录中创建一个目录 mydir 。这是另一个示例 -
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
此命令在目录 /tmp 中创建目录 test-dir 。如果 mkdir 命令成功创建了请求的目录,则不会产生任何输出。
This command creates the directory test-dir in the /tmp directory. The mkdir command produces no output if it successfully creates the requested directory.
如果您在命令行上给出了多个目录, mkdir 将创建每个目录。例如,-
If you give more than one directory on the command line, mkdir creates each of the directories. For example, −
$mkdir docs pub
$
在当前目录下创建目录 docs 和 pub。
Creates the directories docs and pub under the current directory.
Creating Parent Directories
我们现在将了解如何创建父目录。有时,当您要创建目录时,它的父目录或目录可能不存在。在这种情况下, mkdir 会发出如下错误消息 -
We will now understand how to create parent directories. Sometimes when you want to create a directory, its parent directory or directories might not exist. In this case, mkdir issues an error message as follows −
$mkdir /tmp/amrood/test
mkdir: Failed to make directory "/tmp/amrood/test";
No such file or directory
$
在这种情况下,可以将 -p 选项指定给 mkdir 命令。它会为您创建所有必要的目录。例如 -
In such cases, you can specify the -p option to the mkdir command. It creates all the necessary directories for you. For example −
$mkdir -p /tmp/amrood/test
$
以上命令创建所有必需的父目录。
The above command creates all the required parent directories.
Removing Directories
可以使用 rmdir 命令以如下方式删除目录 -
Directories can be deleted using the rmdir command as follows −
$rmdir dirname
$
Note - 要删除目录,请确保它为空,这意味着该目录中不应有任何文件或子目录。
Note − To remove a directory, make sure it is empty which means there should not be any file or sub-directory inside this directory.
您可以一次删除多个目录,如下所示 -
You can remove multiple directories at a time as follows −
$rmdir dirname1 dirname2 dirname3
$
如果以上目录为空,则该命令将删除目录 dirname1、dirname2 和 dirname3。如果成功, rmdir 命令不会产生输出。
The above command removes the directories dirname1, dirname2, and dirname3, if they are empty. The rmdir command produces no output if it is successful.
Changing Directories
除了更改到主目录之外,还可以使用 cd 命令执行更多操作。您可以通过指定有效的绝对或相对路径来使用它更改到任何目录。语法如下 -
You can use the cd command to do more than just change to a home directory. You can use it to change to any directory by specifying a valid absolute or relative path. The syntax is as given below −
$cd dirname
$
此处, dirname 是你希望更改为的目录名称。例如,命令 −
Here, dirname is the name of the directory that you want to change to. For example, the command −
$cd /usr/local/bin
$
更改为目录 /usr/local/bin 。在这个目录中,你可以使用以下路径进行 cd 至目录 /usr/home/amrood −
Changes to the directory /usr/local/bin. From this directory, you can cd to the directory /usr/home/amrood using the following relative path −
$cd ../../home/amrood
$
Renaming Directories
mv (move) 命令还可以用于重命名目录。语法如下 −
The mv (move) command can also be used to rename a directory. The syntax is as follows −
$mv olddir newdir
$
你可以将目录 mydir 重命名为 yourdir ,如下 −
You can rename a directory mydir to yourdir as follows −
$mv mydir yourdir
$
The directories . (dot) and .. (dot dot)
filename . (点)表示当前工作目录; filename .. (双点)表示高于当前工作目录一级,通常称为父目录。
The filename . (dot) represents the current working directory; and the filename .. (dot dot) represents the directory one level above the current working directory, often referred to as the parent directory.
如果我们输入命令来显示当前工作目录/文件的列表并使用 -a option 来列出所有文件和 -l option 提供长列表,我们将会收到以下结果。
If we enter the command to show a listing of the current working directories/files and use the -a option to list all the files and the -l option to provide the long listing, we will receive the following result.
$ls -la
drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 .
drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
---------- 1 teacher class 4210 May 1 08:27 .profile
-rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo
$
Unix - File Permission / Access Modes
在本章中,我们将详细讨论 Unix 中的文件权限和访问模式。文件所有权是 Unix 的一个重要组成部分,它提供了一种安全的文件存储方法。Unix 中的每个文件都具有以下属性 −
In this chapter, we will discuss in detail about file permission and access modes in Unix. File ownership is an important component of Unix that provides a secure method for storing files. Every file in Unix has the following attributes −
-
Owner permissions − The owner’s permissions determine what actions the owner of the file can perform on the file.
-
Group permissions − The group’s permissions determine what actions a user, who is a member of the group that a file belongs to, can perform on the file.
-
Other (world) permissions − The permissions for others indicate what action all other users can perform on the file.
The Permission Indicators
使用 ls -l 命令时,它会显示与文件权限相关的各种信息,如下所示 −
While using ls -l command, it displays various information related to file permission as follows −
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
这里,第一列表示不同的访问模式,即文件或目录具有的权限。
Here, the first column represents different access modes, i.e., the permission associated with a file or a directory.
权限分为每组 3 个,组中的每个位置都表示一个特定权限,其顺序如下:读 (r)、写 (w)、执行 (x) −
The permissions are broken into groups of threes, and each position in the group denotes a specific permission, in this order: read (r), write (w), execute (x) −
-
The first three characters (2-4) represent the permissions for the file’s owner. For example, -rwxr-xr-- represents that the owner has read (r), write (w) and execute (x) permission.
-
The second group of three characters (5-7) consists of the permissions for the group to which the file belongs. For example, -rwxr-xr-- represents that the group has read (r) and execute (x) permission, but no write permission.
-
The last group of three characters (8-10) represents the permissions for everyone else. For example, -rwxr-xr-- represents that there is read (r) only permission.
File Access Modes
文件的权限是 Unix 系统安全的第一道防线。Unix 权限的基本构建块是这里描述的 read 、 write 和 execute 权限 −
The permissions of a file are the first line of defense in the security of a Unix system. The basic building blocks of Unix permissions are the read, write, and execute permissions, which have been described below −
Directory Access Modes
目录访问模式的列出和组织方式与任何其他文件相同。需要注意以下几个区别 −
Directory access modes are listed and organized in the same manner as any other file. There are a few differences that need to be mentioned −
Read
访问目录表示用户可以读取内容。用户可以查看目录中的 filenames 。
Access to a directory means that the user can read the contents. The user can look at the filenames inside the directory.
Changing Permissions
要更改文件或目录许可权,请使用 chmod (更改模式)命令。有两种使用 chmod 的方法——符号模式和绝对模式。
To change the file or the directory permissions, you use the chmod (change mode) command. There are two ways to use chmod — the symbolic mode and the absolute mode.
Using chmod in Symbolic Mode
初学者修改文件或目录权限最简单的方法是使用符号模式。有了符号权限,您可以使用下表中的运算符来添加、删除或指定您想要的权限组。
The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode. With symbolic permissions you can add, delete, or specify the permission set you want by using the operators in the following table.
Sr.No. |
Chmod operator & Description |
1 |
+ Adds the designated permission(s) to a file or directory. |
2 |
- Removes the designated permission(s) from a file or directory. |
3 |
= Sets the designated permission(s). |
这里有一个使用 testfile 的示例。在 testfile 中运行 ls -1 显示文件的权限如下 −
Here’s an example using testfile. Running ls -1 on the testfile shows that the file’s permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
然后对 testfile 运行前面的表中的每个 chmod 命令示例,然后执行 ls –l ,这样您就可以看到权限更改 −
Then each example chmod command from the preceding table is run on the testfile, followed by ls –l, so you can see the permission changes −
$chmod o+wx testfile
$ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
以下是如何将这些命令组合在单行中 −
Here’s how you can combine these commands on a single line −
$chmod o+wx,u-x,g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Using chmod with Absolute Permissions
使用 chmod 命令修改权限的第二种方法是使用数字来指定文件每组权限。
The second way to modify permissions with the chmod command is to use a number to specify each set of permissions for the file.
每项权限都分配有一个值,如下表所示,每组权限的总和都为该组提供了一个数字。
Each permission is assigned a value, as the following table shows, and the total of each set of permissions provides a number for that set.
Number |
Octal Permission Representation |
Ref |
0 |
No permission |
--- |
1 |
Execute permission |
--x |
2 |
Write permission |
-w- |
3 |
Execute and write permission: 1 (execute) + 2 (write) = 3 |
-wx |
4 |
Read permission |
r-- |
5 |
Read and execute permission: 4 (read) + 1 (execute) = 5 |
r-x |
6 |
Read and write permission: 4 (read) + 2 (write) = 6 |
rw- |
7 |
All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 |
rwx |
这里有一个使用 testfile 的示例。在 testfile 中运行 ls -1 显示文件的权限如下 −
Here’s an example using the testfile. Running ls -1 on the testfile shows that the file’s permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
然后对 testfile 运行前面的表中的每个 chmod 命令示例,然后执行 ls –l ,这样您就可以看到权限更改 −
Then each example chmod command from the preceding table is run on the testfile, followed by ls –l, so you can see the permission changes −
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 amrood users 1024 Nov 2 00:10 testfile
Changing Owners and Groups
在 Unix 中创建帐户时,它会为每个用户分配一个 owner ID 和一个 group ID 。上述所有权限也都根据所有者和组进行分配。
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the permissions mentioned above are also assigned based on the Owner and the Groups.
有两个可用的命令来更改文件的所属者和组 −
Two commands are available to change the owner and the group of files −
-
chown − The chown command stands for "change owner" and is used to change the owner of a file.
-
chgrp − The chgrp command stands for "change group" and is used to change the group of a file.
Changing Ownership
chown 命令更改文件的拥有权。其基本语法如下:
The chown command changes the ownership of a file. The basic syntax is as follows −
$ chown user filelist
用户的代码值可以是系统上的 name of a user 或系统上用户的 user id (uid) 。
The value of the user can be either the name of a user on the system or the user id (uid) of a user on the system.
以下示例将帮助你了解这个概念:
The following example will help you understand the concept −
$ chown amrood testfile
$
将给定文件的所有者更改为用户 amrood 。
Changes the owner of the given file to the user amrood.
NOTE - 超级用户 root 拥有更改任何文件所有权的非受限能力,但普通用户只能更改由自己拥有的文件的所有权。
NOTE − The super user, root, has the unrestricted capability to change the ownership of any file but normal users can change the ownership of only those files that they own.
Changing Group Ownership
chgrp 命令更改文件的组所有权。其基本语法如下:
The chgrp command changes the group ownership of a file. The basic syntax is as follows −
$ chgrp group filelist
组的代码值可以是系统上的 name of a group 或系统上的组的 the group ID (GID) 。
The value of group can be the name of a group on the system or the group ID (GID) of a group on the system.
以下示例将帮助你了解这个概念:
Following example helps you understand the concept −
$ chgrp special testfile
$
将给定文件的组更改为 special 组。
Changes the group of the given file to special group.
SUID and SGID File Permission
通常,一个命令在执行时都需要利用特殊权限才能完成其任务。
Often when a command is executed, it will have to be executed with special privileges in order to accomplish its task.
举例来说,当用 passwd 命令更改口令时,你的新口令会存储在文件 /etc/shadow 中。
As an example, when you change your password with the passwd command, your new password is stored in the file /etc/shadow.
由于安全原因,作为一个普通用户,你没有对这个文件的 read 或 write 访问权,但是当你更改你的口令时,你需要有这个文件的写权限。这意味着 passwd 程序需要给你其他权限,才能写文件 /etc/shadow 。
As a regular user, you do not have read or write access to this file for security reasons, but when you change your password, you need to have the write permission to this file. This means that the passwd program has to give you additional permissions so that you can write to the file /etc/shadow.
通过一种称为 Set User ID (SUID) 和 Set Group ID (SGID) 位的机制给程序额外权限。
Additional permissions are given to programs via a mechanism known as the Set User ID (SUID) and Set Group ID (SGID) bits.
当一个有 SUID 位的程序执行时,你将继承该程序所有者的权限。没有 SUID 位的程序将以启动该程序的用户的权限运行。
When you execute a program that has the SUID bit enabled, you inherit the permissions of that program’s owner. Programs that do not have the SUID bit set are run with the permissions of the user who started the program.
SGID 也是如此。通常,一个程序会以你的组权限执行,但是对这个程序,你的组将更改为程序的程序组所有者。
This is the case with SGID as well. Normally, programs execute with your group permissions, but instead your group will be changed just for this program to the group owner of the program.
如果权限可用,SUID 和 SGID 位将显示为字母 "s" 。SUID "s" 位将位于所有者 execute 权限通常所在的权限位中。
The SUID and SGID bits will appear as the letter "s" if the permission is available. The SUID "s" bit will be located in the permission bits where the owners’ execute permission normally resides.
例如,此命令
For example, the command −
$ ls -l /usr/bin/passwd
-r-sr-xr-x 1 root bin 19031 Feb 7 13:47 /usr/bin/passwd*
$
显示 SUID 位已设置,并且该命令归根拥有。在执行位置的大写字母 S (而非小写字母 s )表示未设置执行位。
Shows that the SUID bit is set and that the command is owned by the root. A capital letter S in the execute position instead of a lowercase s indicates that the execute bit is not set.
如果为目录启用了粘滞位,则只有下列用户之一才能删除文件:
If the sticky bit is enabled on the directory, files can only be removed if you are one of the following users −
-
The owner of the sticky directory
-
The owner of the file being removed
-
The super user, root
要为任何目录设置 SUID 和 SGID 位,请尝试以下命令:
To set the SUID and SGID bits for any directory try the following command −
$ chmod ug+s dirname
$ ls -l
drwsr-sr-x 2 root root 4096 Jun 19 06:45 dirname
$
Unix - Environment
在本章中,我们将详细讨论 Unix 环境。一个重要的 Unix 概念是 environment ,它由环境变量定义。有些是由系统设置的,有些是你设置的,还有些是由 shell 或加载另一个程序的任何程序设置的。
In this chapter, we will discuss in detail about the Unix environment. An important Unix concept is the environment, which is defined by environment variables. Some are set by the system, others by you, yet others by the shell, or any program that loads another program.
变量是一个我们向其分配值的字符串。分配的值可以是数字、文本、文件名、设备或任何其他类型的数据。
A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.
例如,我们首先设置变量 TEST,然后使用 echo 命令访问其值 −
For example, first we set a variable TEST and then we access its value using the echo command −
$TEST="Unix Programming"
$echo $TEST
产生以下结果。
It produces the following result.
Unix Programming
请注意,设置环境变量时不用 $ 标号,但访问它们时用的前缀是 $ 标号。这些变量保留其值,直到我们退出 shell。
Note that the environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix. These variables retain their values until we come out of the shell.
登录系统时,shell 会经过称为 initialization 的阶段来设置环境。这通常是一个分两步的过程,涉及 shell 读取以下文件−
When you log in to the system, the shell undergoes a phase called initialization to set up the environment. This is usually a two-step process that involves the shell reading the following files −
-
/etc/profile
-
profile
此过程如下−
The process is as follows −
-
The shell checks to see whether the file /etc/profile exists.
-
If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed.
-
The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in.
-
If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed.
这两个文件都已读取完毕后,shell 会显示一个提示−
As soon as both of these files have been read, the shell displays a prompt −
$
这是一个提示,您可以在此处输入命令,以让他们执行。
This is the prompt where you can enter commands in order to have them executed.
Note −此处详细说明的 shell 初始化过程适用于所有 Bourne 类型的 shell,但 bash 和 ksh 使用了一些另外的文件。
Note − The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used by bash and ksh.
The .profile File
文件 /etc/profile 由 Unix 电脑的系统管理员维护,其中包含系统上的所有用户所需的 shell 初始化信息。
The file /etc/profile is maintained by the system administrator of your Unix machine and contains shell initialization information required by all users on a system.
文件 .profile 受您控制。您可以向此文件添加任意多的 shell 自定义信息。您需要配置的最少信息包括−
The file .profile is under your control. You can add as much shell customization information as you want to this file. The minimum set of information that you need to configure includes −
-
The type of terminal you are using.
-
A list of directories in which to locate the commands.
-
A list of variables affecting the look and feel of your terminal.
你可以在家目录中查看 .profile 。使用 vi 编辑器将其打开,并查看为你的环境设置的所有变量。
You can check your .profile available in your home directory. Open it using the vi editor and check all the variables set for your environment.
Setting the Terminal Type
通常,你正在使用的终端类型会由 login 或 getty 程序自动配置。有时,自动配置过程会错误猜测你的终端。
Usually, the type of terminal you are using is automatically configured by either the login or getty programs. Sometimes, the auto configuration process guesses your terminal incorrectly.
如果你的终端设置错误,则命令的输出可能看起来很奇怪,或者你可能无法与 shell 正确交互。
If your terminal is set incorrectly, the output of the commands might look strange, or you might not be able to interact with the shell properly.
为了确保这种情况不会发生,大多数用户以以下方式将他们的终端设置为最低公分母 −
To make sure that this is not the case, most users set their terminal to the lowest common denominator in the following way −
$TERM=vt100
$
Setting the PATH
当你 فى موجه الأوامر تكتب أى أمر، يتعين على الشل العثور على الأمر قبل تنفيذه.
When you type any command on the command prompt, the shell has to locate the command before it can be executed.
يوضح متغير PATH المواقع التى يجب أن يبحث فيها الشل عن الأوامر. وعادة ما يتم تعيين متغير المسار كما يلى −
The PATH variable specifies the locations in which the shell should look for commands. Usually the Path variable is set as follows −
$PATH=/bin:/usr/bin
$
هنا، كل مدخلة فردية مفصولة بواسطة حرف النقطتين (:) هى دلائل. إذا طلبت من الشل تنفيذ أمر ولم يتمكن من العثور عليه فى أى من الدلائل المحددة فى متغير المسار، ستظهر رسالة مشابهة لما يلى −
Here, each of the individual entries separated by the colon character (:) are directories. If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, a message similar to the following appears −
$hello
hello: not found
$
هناك متغيرات مثل PS1 و PS2 يتم مناقشتها فى القسم التالى.
There are variables like PS1 and PS2 which are discussed in the next section.
PS1 and PS2 Variables
يتم تخزين الأحرف التى يعرضها الشل على أنه موجه للأوامر فى متغير PS1. يمكنك تغيير هذا المتغير إلى أى شئ تريده. وبمجرد تغييره، سيستخدمه الشل من تلك النقطة فصاعدًا.
The characters that the shell displays as your command prompt are stored in the variable PS1. You can change this variable to be anything you want. As soon as you change it, it’ll be used by the shell from that point on.
على سبيل المثال، إذا أصدرت الأمر −
For example, if you issued the command −
$PS1='=>'
=>
=>
=>
سيصبح موجه الأوامر الخاص بك ⇒. لتعيين قيمة PS1 بحيث تعرض دليل العمل، أصدر الأمر −
Your prompt will become ⇒. To set the value of PS1 so that it shows the working directory, issue the command −
=>PS1="[\u@\h \w]\$"
[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$
[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$
ويتمخض عن هذا الأمر إظهار موجه المستخدم لاسم المستخدم واسم الجهاز (اسم المضيف) ودليل العمل.
The result of this command is that the prompt displays the user’s username, the machine’s name (hostname), and the working directory.
يوجد عدد غير قليل من escape sequences التى يمكن استخدامها كحجج قيمة لـ PS1؛ حاول أن تقصر نفسك على الأكثر أهمية حتى لا يغمرك الموجه بالمعلومات.
There are quite a few escape sequences that can be used as value arguments for PS1; try to limit yourself to the most critical so that the prompt does not overwhelm you with information.
Sr.No. |
Escape Sequence & Description |
1 |
\t Current time, expressed as HH:MM:SS |
2 |
\d Current date, expressed as Weekday Month Date |
3 |
\n Newline |
4 |
\s Current shell environment |
5 |
\W Working directory |
6 |
\w Full path of the working directory |
7 |
\u Current user’s username |
8 |
\h Hostname of the current machine |
9 |
\# Command number of the current command. Increases when a new command is entered |
10 |
\$ If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $ sign |
每次登录时,您都可以自己进行更改,或者可以在 .profile 文件中添加更改使其在 PS1 中自动进行。
You can make the change yourself every time you log in, or you can have the change made automatically in PS1 by adding it to your .profile file.
发出不完整的命令时,外壳将显示一个次要提示符,并等待您完成命令并再次按下 Enter 。
When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enter again.
默认的次要提示符是 > (大于号),但可以通过重新定义 PS2 外壳变量进行更改 −
The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable −
以下是使用默认次要提示符的示例 −
Following is the example which uses the default secondary prompt −
$ echo "this is a
> test"
this is a
test
$
下面给出的示例使用自定义提示符重新定义了 PS2 −
The example given below re-defines PS2 with a customized prompt −
$ PS2="secondary prompt->"
$ echo "this is a
secondary prompt->test"
this is a
test
$
Environment Variables
以下是重要环境变量的部分列表。这些变量按如下所述设置和访问 −
Following is the partial list of important environment variables. These variables are set and accessed as mentioned below −
Sr.No. |
Variable & Description |
1 |
DISPLAY Contains the identifier for the display that X11 programs should use by default. |
2 |
HOME Indicates the home directory of the current user: the default argument for the cd built-in command. |
3 |
IFS Indicates the Internal Field Separator that is used by the parser for word splitting after expansion. |
4 |
LANG LANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil. |
5 |
LD_LIBRARY_PATH A Unix system with a dynamic linker, contains a colonseparated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories. |
6 |
PATH Indicates the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. |
7 |
PWD Indicates the current working directory as set by the cd command. |
8 |
RANDOM Generates a random integer between 0 and 32,767 each time it is referenced. |
9 |
SHLVL Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session. |
10 |
TERM Refers to the display type. |
11 |
TZ Refers to Time zone. It can take values like GMT, AST, etc. |
12 |
UID Expands to the numeric user ID of the current user, initialized at the shell startup. |
以下是显示几个环境变量的示例 -
Following is the sample example showing few environment variables −
$ echo $HOME
/root
]$ echo $DISPLAY
$ echo $TERM
xterm
$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin
$
Unix Basic Utilities - Printing, Email
在本章中,我们将详细讨论 Unix 基本实用工具中的打印和电子邮件。到目前为止,我们已尝试了解 Unix 操作系统及其基本命令的本质。在本章中,我们将学习一些可在日常生活中使用的重要 Unix 实用工具。
In this chapter, we will discuss in detail about Printing and Email as the basic utilities of Unix. So far, we have tried to understand the Unix OS and the nature of its basic commands. In this chapter, we will learn some important Unix utilities that can be used in our day-to-day life.
Printing Files
在 Unix 系统上打印文件之前,你可能希望重新整理格式以调整页边距、突出显示一些单词等。大多数文件也可以在不重新整理格式的情况下打印,但打印的原始文件可能并不可取。
Before you print a file on a Unix system, you may want to reformat it to adjust the margins, highlight some words, and so on. Most files can also be printed without reformatting, but the raw printout may not be that appealing.
许多版本的 Unix 包含两个功能强大的文本格式化程序, nroff 和 troff 。
Many versions of Unix include two powerful text formatters, nroff and troff.
The pr Command
pr 命令在终端屏幕或打印机上对文件进行微调格式。例如,如果你有一个文件中的长名字列表,你可以将其格式化到屏幕分别成两列或更多列。
The pr command does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns.
以下是 pr 命令的语法 −
Following is the syntax for the pr command −
pr option(s) filename(s)
pr 仅在屏幕或打印副本上更改文件的格式;它不会修改原始文件。下表列出了一些 pr 选项 −
The pr changes the format of the file only on the screen or on the printed copy; it doesn’t modify the original file. Following table lists some pr options −
Sr.No. |
Option & Description |
1 |
-k Produces k columns of output |
2 |
-d Double-spaces the output (not on all pr versions) |
3 |
-h "header" Takes the next item as a report header |
4 |
-t Eliminates the printing of header and the top/bottom margins |
5 |
-l PAGE_LENGTH Sets the page length to PAGE_LENGTH (66) lines. The default number of lines of text is 56 |
6 |
-o MARGIN Offsets each line with MARGIN (zero) spaces |
7 |
-w PAGE_WIDTH Sets the page width to PAGE_WIDTH (72) characters for multiple text-column output only |
在使用 pr 之前,以下为一个名为 food 的示例文件的内容。
Before using pr, here are the contents of a sample file named food.
$cat food
Sweet Tooth
Bangkok Wok
Mandalay
Afghani Cuisine
Isle of Java
Big Apple Deli
Sushi and Sashimi
Tio Pepe's Peppers
........
$
让我们使用 pr 命令创建一个带 Restaurants − 头部的两列报告
Let’s use the pr command to make a two-column report with the header Restaurants −
$pr -2 -h "Restaurants" food
Nov 7 9:58 1997 Restaurants Page 1
Sweet Tooth Isle of Java
Bangkok Wok Big Apple Deli
Mandalay Sushi and Sashimi
Afghani Cuisine Tio Pepe's Peppers
........
$
The lp and lpr Commands
命令 lp 或 lpr 会将文件打印在纸上,而不是屏幕上显示。一旦使用 pr 命令对格式进行设置,便可以使用以下任何命令将文件打印到连接到计算机的打印机上。
The command lp or lpr prints a file onto paper as opposed to the screen display. Once you are ready with formatting using the pr command, you can use any of these commands to print your file on the printer connected to your computer.
你的系统管理员很可能已在你的站点设置了默认的打印机。若要在默认打印机上打印名为 food 的文件,请像以下示例那样使用 lp 或 lpr 命令 −
Your system administrator has probably set up a default printer at your site. To print a file named food on the default printer, use the lp or lpr command, as in the following example −
$lp food
request id is laserp-525 (1 file)
$
lp 命令会显示一个 ID,可用于取消打印作业或查看作业状态。
The lp command shows an ID that you can use to cancel the print job or check its status.
-
If you are using the lp command, you can use the -n*Num* option to print Num number of copies. Along with the command lpr, you can use -Num for the same.
-
If there are multiple printers connected with the shared network, then you can choose a printer using -d*printer* option along with lp command and for the same purpose you can use -P*printer* option along with lpr command. Here printer is the printer name.
The lpstat and lpq Commands
lpstat 命令显示打印机队列中的内容:请求 ID、所有者、文件大小、发送打印作业的时间,以及请求的状态。
The lpstat command shows what’s in the printer queue: request IDs, owners, file sizes, when the jobs were sent for printing, and the status of the requests.
如果你想查看除自己以外的所有输出请求,请使用 lpstat -o 。请求按打印顺序显示 −
Use lpstat -o if you want to see all output requests other than just your own. Requests are shown in the order they’ll be printed −
$lpstat -o
laserp-573 john 128865 Nov 7 11:27 on laserp
laserp-574 grace 82744 Nov 7 11:28
laserp-575 john 23347 Nov 7 11:35
$
lpq 提供的信息与 lpstat -o 略有不同 −
The lpq gives slightly different information than lpstat -o −
$lpq
laserp is ready and printing
Rank Owner Job Files Total Size
active john 573 report.ps 128865 bytes
1st grace 574 ch03.ps ch04.ps 82744 bytes
2nd john 575 standard input 23347 bytes
$
此处第一行显示打印机状态。如果打印机已禁用或缺纸,你可能在此第一行看到不同的消息。
Here the first line displays the printer status. If the printer is disabled or running out of paper, you may see different messages on this first line.
The cancel and lprm Commands
命令 cancel 可从 lp command 终结打印请求。 lprm 命令可终结所有 lpr requests 。你可以指定请求 ID(由 lp 或 lpq 显示)或打印机名称。
The cancel command terminates a printing request from the lp command. The lprm command terminates all lpr requests. You can specify either the ID of the request (displayed by lp or lpq) or the name of the printer.
$cancel laserp-575
request "laserp-575" cancelled
$
要取消当前正在打印的任何请求,无论其 ID 如何,只需输入 cancel 和打印机名称 −
To cancel whatever request is currently printing, regardless of its ID, simply enter cancel and the printer name −
$cancel laserp
request "laserp-573" cancelled
$
lprm 命令会在活动作业属于你的情况下将其取消。否则,你可以将作业号作为参数给出,或使用 dash (-) 删除你的所有作业 −
The lprm command will cancel the active job if it belongs to you. Otherwise, you can give job numbers as arguments, or use a dash (-) to remove all of your jobs −
$lprm 575
dfA575diamond dequeued
cfA575diamond dequeued
$
lprm 命令会告诉你实际从打印机队列中删除的文件名。
The lprm command tells you the actual filenames removed from the printer queue.
Sending Email
你使用终端邮件命令来发送和接收邮件。以下是发送电子邮件的语法 −
You use the Unix mail command to send and receive mail. Here is the syntax to send an email −
$mail [-s subject] [-c cc-addr] [-b bcc-addr] to-addr
以下是与邮件命令相关的部分重要选项 −s
Here are important options related to mail command −s
Sr.No. |
Option & Description |
1 |
-s Specifies subject on the command line. |
2 |
-c Sends carbon copies to the list of users. List should be a commaseparated list of names. |
3 |
-b Sends blind carbon copies to list. List should be a commaseparated list of names. |
以下是一个将测试消息发送给 admin@yahoo.com 的示例。
Following is an example to send a test message to admin@yahoo.com.
$mail -s "Test Message" admin@yahoo.com
然后,您需要在行首键入您的消息,后跟 "control-D" 。要停止,只需键入点 (.) ,如下所示 −
You are then expected to type in your message, followed by "control-D" at the beginning of a line. To stop, simply type dot (.) as follows −
Hi,
This is a test
.
Cc:
您可以使用 redirect < operator 发送完整文件,如下所示 −
You can send a complete file using a redirect < operator as follows −
$mail -s "Report 05/06/07" admin@yahoo.com < demo.txt
要检查 Unix 系统中的传入电子邮件,只需键入电子邮件,如下所示 −
To check incoming email at your Unix system, you simply type email as follows −
$mail
no email
Unix - Pipes and Filters
在本章中,我们将详细讨论 Unix 中的管道和过滤器。您可以将两个命令连接在一起,这样来自一个程序的输出就成为下一个程序的输入。以这种方式连接的两个或更多个命令形成一个管道。
In this chapter, we will discuss in detail about pipes and filters in Unix. You can connect two commands together so that the output from one program becomes the input of the next program. Two or more commands connected in this way form a pipe.
要创建一个管道,请在两个命令之间的命令行上放置一个垂直线 ( | )。
To make a pipe, put a vertical bar (|) on the command line between two commands.
当一个程序从另一个程序获取其输入时,它也会对该输入执行某些操作,并将结果写入标准输出。它被称为 filter 。
When a program takes its input from another program, it performs some operation on that input, and writes the result to the standard output. It is referred to as a filter.
The grep Command
grep 命令搜索一个或多个文件中包含特定模式的行。语法如下 −
The grep command searches a file or files for lines that have a certain pattern. The syntax is −
$grep pattern file(s)
名称 "grep" 来自 ed(Unix 行编辑器)命令 g/re/p ,它表示“全局搜索正则表达式,并打印包含该正则表达式的所有行”。
The name "grep" comes from the ed (a Unix line editor) command g/re/p which means “globally search for a regular expression and print all lines containing it”.
正则表达式不是普通文本(例如,一个单词)就是用来模式匹配的特殊字符。
A regular expression is either some plain text (a word, for example) and/or special characters used for pattern matching.
grep 最简单的用法是查找由单个单词组成的模式。它可以在管道中使用,这样一来只有包含给定字符串的输入文件中的那些行才会发送到标准输出。如果你不给 grep 一个文件名来读取,它会读取其标准输入;所有过滤器程序都采用这种工作方式 −
The simplest use of grep is to look for a pattern consisting of a single word. It can be used in a pipe so that only those lines of the input files containing a given string are sent to the standard output. If you don’t give grep a filename to read, it reads its standard input; that’s the way all filter programs work −
$ls -l | grep "Aug"
-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
$
有各种选项可以与 grep 命令一同使用 −
There are various options which you can use along with the grep command −
Sr.No. |
Option & Description |
1 |
-v Prints all lines that do not match pattern. |
2 |
-n Prints the matched line and its line number. |
3 |
-l Prints only the names of files with matching lines (letter "l") |
4 |
-c Prints only the count of matching lines. |
5 |
-i Matches either upper or lowercase. |
现在,让我们使用一个正则表达式,告诉 grep 查找带有 "carol" 的行,然后是正则表达式中缩写为“.*”的零个或其他字符,然后是“Aug”。−
Let us now use a regular expression that tells grep to find lines with "carol", followed by zero or other characters abbreviated in a regular expression as ".*"), then followed by "Aug".−
在这里,我们使用 -i 选项执行不区分大小写的搜索 −
Here, we are using the -i option to have case insensitive search −
$ls -l | grep -i "carol.*aug"
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
$
The sort Command
sort 命令按字母或数字顺序排列文本行。以下示例对 food 文件中的行进行分类 −
The sort command arranges lines of text alphabetically or numerically. The following example sorts the lines in the food file −
$sort food
Afghani Cuisine
Bangkok Wok
Big Apple Deli
Isle of Java
Mandalay
Sushi and Sashimi
Sweet Tooth
Tio Pepe's Peppers
$
默认情况下, sort 命令按字母顺序排列文本行。有许多选项控制分类 −
The sort command arranges lines of text alphabetically by default. There are many options that control the sorting −
Sr.No. |
Description |
1 |
-n Sorts numerically (example: 10 will sort after 2), ignores blanks and tabs. |
2 |
-r Reverses the order of sort. |
3 |
-f Sorts upper and lowercase together. |
4 |
+x Ignores first x fields when sorting. |
可以将两个以上命令链接到管道中。以使用 grep 时先前的管道为例,我们可以进一步按大小对 8 月修改的文件进行分类。
More than two commands may be linked up into a pipe. Taking a previous pipe example using grep, we can further sort the files modified in August by the order of size.
以下管道包括命令 ls 、 grep 和 sort −
The following pipe consists of the commands ls, grep, and sort −
$ls -l | grep "Aug" | sort +4n
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02
$
此管道按大小对 8 月修改的目录中所有文件进行分类,并将它们打印在终端屏幕上。排序选项 +4n 跳过 4 个字段(字段由空格分隔),然后按数字顺序对行进行排序。
This pipe sorts all files in your directory modified in August by the order of size, and prints them on the terminal screen. The sort option +4n skips four fields (fields are separated by blanks) then sorts the lines in numeric order.
The pg and more Commands
通常您可以将长输出在屏幕上压缩,但如果您通过更多或将 pg 命令用作过滤器来运行文本;当屏幕满载文本后,显示就停止。
A long output can normally be zipped by you on the screen, but if you run text through more or use the pg command as a filter; the display stops once the screen is full of text.
假设您有一个长目录列表。要使读取排序的列表更容易,将输出通过 more 进行管道处理,如下所示 −
Let’s assume that you have a long directory listing. To make it easier to read the sorted listing, pipe the output through more as follows −
$ls -l | grep "Aug" | sort +4n | more
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-r-- 1 john doc 14827 Aug 9 12:40 ch03
.
.
.
-rw-rw-rw- 1 john doc 16867 Aug 6 15:56 ch05
--More--(74%)
当屏幕满载由文件大小顺序排序的行组成的文本时,屏幕将填满。屏幕底部是 more 提示符,您可以在其中键入命令以移动已排序的文本。
The screen will fill up once the screen is full of text consisting of lines sorted by the order of the file size. At the bottom of the screen is the more prompt, where you can type a command to move through the sorted text.
完成后,您可以使用 more 程序的讨论中列出的任何命令。
Once you’re done with this screen, you can use any of the commands listed in the discussion of the more program.
Unix - Processes Management
在本章中,我们将详细讨论 Unix 中的进程管理。当你在 Unix 系统中执行程序时,系统会为该程序创建一个特殊环境。此环境包含系统运行该程序所需的一切,就好像系统中没有其他程序在运行一样。
In this chapter, we will discuss in detail about process management in Unix. When you execute a program on your Unix system, the system creates a special environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system.
在 Unix 中发出命令时,它会创建一个新的进程或者启动一个新的进程。当你尝试 ls 命令以列出目录内容时,你就已经启动了一个进程。进程简单来说是正在运行的程序的一个实例。
Whenever you issue a command in Unix, it creates, or starts, a new process. When you tried out the ls command to list the directory contents, you started a process. A process, in simple terms, is an instance of a running program.
操作系统通过一个五位数的 ID 号来跟踪进程,该 ID 号被称为 pid 或 process ID 。系统中的每个进程都有一个唯一的 pid 。
The operating system tracks processes through a five-digit ID number known as the pid or the process ID. Each process in the system has a unique pid.
由于用尽了所有可能的数字,下一个 pid 将滚动或重新开始,所以 pid 最终会重复。在任何时间点,系统中都无法存在两个 pid 相同的进程,因为 pid 是 Unix 用来跟踪每个进程的。
Pids eventually repeat because all the possible numbers are used up and the next pid rolls or starts over. At any point of time, no two processes with the same pid exist in the system because it is the pid that Unix uses to track each process.
Starting a Process
启动进程(运行命令)时,有两种方法可以运行它 −
When you start a process (run a command), there are two ways you can run it −
-
Foreground Processes
-
Background Processes
Foreground Processes
默认情况下,你启动的每个进程都在前台运行。它从键盘获取输入,并将输出发送到屏幕上。
By default, every process that you start runs in the foreground. It gets its input from the keyboard and sends its output to the screen.
你可以看到这是通过 ls 命令实现的。如果你希望列出你当前目录中的所有文件,可以使用以下命令 −
You can see this happen with the ls command. If you wish to list all the files in your current directory, you can use the following command −
$ls ch*.doc
这将显示所有名称以 ch 开头并以 .doc 结尾的文件 −
This would display all the files, the names of which start with ch and end with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
进程在前台运行时,输出将定向到我的屏幕上,如果 ls 命令需要任何输入(实际上并不需要),它会从键盘上等待输入。
The process runs in the foreground, the output is directed to my screen, and if the ls command wants any input (which it does not), it waits for it from the keyboard.
当程序在前台运行且耗时时,不能运行任何其他命令(启动任何其他进程),因为提示符在程序完成处理并退出之前都是不可用的。
While a program is running in the foreground and is time-consuming, no other commands can be run (start any other processes) because the prompt would not be available until the program finishes processing and comes out.
Background Processes
后台进程运行时无需连接到你的键盘。如果后台进程需要任何键盘输入,它会等待。
A background process runs without being connected to your keyboard. If the background process requires any keyboard input, it waits.
在后台运行进程的优势在于,你可以运行其他命令;你无需等待它完成即可开始另一个命令!
The advantage of running a process in the background is that you can run other commands; you do not have to wait until it completes to start another!
启动后台进程最简单的方法是在命令末尾添加一个和号 ( & )。
The simplest way to start a background process is to add an ampersand (&) at the end of the command.
$ls ch*.doc &
这会显示所有名称以 ch 开头并以 .doc 结尾的文件 −
This displays all those files the names of which start with ch and end with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc
在此,如果 ls 命令需要任何输入(实际上并不需要),它会进入停止状态,直到我们将其移至前台并从键盘提供数据为止。
Here, if the ls command wants any input (which it does not), it goes into a stop state until we move it into the foreground and give it the data from the keyboard.
第一行包含有关后台进程的信息 - 作业号和进程 ID。你需要了解作业号才能在后台和前台之间对其进行操作。
That first line contains information about the background process - the job number and the process ID. You need to know the job number to manipulate it between the background and the foreground.
按 Enter 键,你将看到以下内容 −
Press the Enter key and you will see the following −
[1] + Done ls ch*.doc &
$
第一行告诉我们, ls 命令的后台进程已成功完成。第二行提示输入另一个命令。
The first line tells you that the ls command background process finishes successfully. The second is a prompt for another command.
Listing Running Processes
运行 ps (进程状态)命令很容易看到您自己的进程,具体如下 −
It is easy to see your own processes by running the ps (process status) command as follows −
$ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps
One of the most commonly used flags for ps is the -f ( f for full) option, which provides more information as shown in the following example −
One of the most commonly used flags for ps is the -f ( f for full) option, which provides more information as shown in the following example −
$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh
amrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f
Here is the description of all the fields displayed by ps -f command −
Here is the description of all the fields displayed by ps -f command −
Sr.No. |
Column & Description |
1 |
UID User ID that this process belongs to (the person running it) |
2 |
PID Process ID |
3 |
PPID Parent process ID (the ID of the process that started it) |
4 |
C CPU utilization of process |
5 |
STIME Process start time |
6 |
TTY Terminal type associated with the process |
7 |
TIME CPU time taken by the process |
8 |
CMD The command that started this process |
与 ps 命令一起使用的其他选项 −
There are other options which can be used along with ps command −
Sr.No. |
Option & Description |
1 |
-a Shows information about all users |
2 |
-x Shows information about processes without terminals |
3 |
-u Shows additional information like -f option |
4 |
-e Displays extended information |
Stopping Processes
以多种不同的方式结束进程。通常,从基于控制台的命令发送 CTRL + C 键击(默认中断字符)将退出该命令。当进程在前景模式下运行时,此方法有效。
Ending a process can be done in several different ways. Often, from a console-based command, sending a CTRL + C keystroke (the default interrupt character) will exit the command. This works when the process is running in the foreground mode.
如果一个进程在后台运行,您应当使用 ps 命令获取其作业 ID。然后,您可以使用 kill 命令按如下方式中止该进程:
If a process is running in the background, you should get its Job ID using the ps command. After that, you can use the kill command to kill the process as follows −
$ps -f
UID PID PPID C STIME TTY TIME CMD
amrood 6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood 6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood 3662 3657 0 08:10:53 pts/6 0:00 -ksh
amrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f
$kill 6738
Terminated
此处, kill 命令中止了 first_one 进程。如果一个进程忽略常规中止命令,则您可以按如下方式使用 kill -9 再跟上进程 ID:
Here, the kill command terminates the first_one process. If a process ignores a regular kill command, you can use kill -9 followed by the process ID as follows −
$kill -9 6738
Terminated
Parent and Child Processes
每个 Unix 进程都有两个分配给它的 ID 号:进程 ID (pid) 和父进程 ID (ppid)。系统中的每个用户进程都有一个父进程。
Each unix process has two ID numbers assigned to it: The Process ID (pid) and the Parent process ID (ppid). Each user process in the system has a parent process.
你运行的大多数命令都以 shell 作为它们的父进程。检查 ps -f 示例,其中此命令列出了进程 ID 和父进程 ID。
Most of the commands that you run have the shell as their parent. Check the ps -f example where this command listed both the process ID and the parent process ID.
Zombie and Orphan Processes
通常,当子进程被杀死时,父进程将通过 SIGCHLD 信号进行更新。然后,父进程可以根据需要执行一些其他任务或重新启动一个新子进程。但是,有时父进程在子进程被杀死之前被杀死。在这种情况下,“所有进程的父进程”( init 进程)变为新的 PPID(父进程 ID)。在某些情况下,这些进程称为孤儿进程。
Normally, when a child process is killed, the parent process is updated via a SIGCHLD signal. Then the parent can do some other task or restart a new child as needed. However, sometimes the parent process is killed before its child is killed. In this case, the "parent of all processes," the init process, becomes the new PPID (parent process ID). In some cases, these processes are called orphan processes.
当进程被杀死时, ps 列表可能仍会显示处于 Z 状态的进程。这是一个僵尸进程或死进程。该进程已死亡且不再使用。这些进程与孤儿进程不同。它们已完成执行,但仍在进程表中找到条目。
When a process is killed, a ps listing may still show the process with a Z state. This is a zombie or defunct process. The process is dead and not being used. These processes are different from the orphan processes. They have completed execution but still find an entry in the process table.
Daemon Processes
守护程序是相关的背景进程,通常使用 root 权限以其他进程的服务请求来运行。
Daemons are system-related background processes that often run with the permissions of root and services requests from other processes.
守护程序不控制本机终端。它无法打开 /dev/tty 。如果您执行 "ps -ef" ,并查看 tty 字段,则所有守护程序的 tty 都为 ? 。
A daemon has no controlling terminal. It cannot open /dev/tty. If you do a "ps -ef" and look at the tty field, all daemons will have a ? for the tty.
准确地说,守护程序是在后台运行,通常等待能够处理的事情发生。例如,打印机守护程序将等待打印命令。
To be precise, a daemon is a process that runs in the background, usually waiting for something to happen that it is capable of working with. For example, a printer daemon waiting for print commands.
如果您有需要大量处理时间的程序,那么将它设为守护程序并在后台运行非常值得。
If you have a program that calls for lengthy processing, then it’s worth to make it a daemon and run it in the background.
The top Command
top 命令是一个非常有用的工具,可以快速按各种条件对进程进行排序。
The top command is a very useful tool for quickly showing processes sorted by various criteria.
它是频繁更新并显示物理和虚拟内存、CPU 使用率、平均负载以及繁忙进程的信息的交互式诊断工具。
It is an interactive diagnostic tool that updates frequently and shows information about physical and virtual memory, CPU usage, load averages, and your busy processes.
以下是运行 top 命令并查看不同进程的 CPU 使用情况统计信息的简单语法 −
Here is the simple syntax to run top command and to see the statistics of CPU utilization by different processes −
$top
Job ID Versus Process ID
后台和暂停进程通常通过 job number (job ID) 进行控制。此号码不同于进程 ID,并且由于更短而使用。
Background and suspended processes are usually manipulated via job number (job ID). This number is different from the process ID and is used because it is shorter.
此外,作业可能包含多个进程,这些进程可能会按顺序或同时并行运行。使用作业 ID 比跟踪各个进程更容易。
In addition, a job can consist of multiple processes running in a series or at the same time, in parallel. Using the job ID is easier than tracking individual processes.
Unix - Network Communication Utilities
在本章中,我们将详细讨论 Unix 中的网络通信实用程序。在分布式环境中工作时,您需要与远程用户通信,还需要访问远程 Unix 计算机。
In this chapter, we will discuss in detail about network communication utilities in Unix. When you work in a distributed environment, you need to communicate with remote users and you also need to access remote Unix machines.
有多种 Unix 实用程序可以帮助用户在联网的分布式环境中进行计算。本章列举了几种实用程序。
There are several Unix utilities that help users compute in a networked, distributed environment. This chapter lists a few of them.
The ping Utility
ping 命令向网络上可用的主机发送回显请求。使用此命令,您可以查看远程主机是否响应良好。
The ping command sends an echo request to a host available on the network. Using this command, you can check if your remote host is responding well or not.
ping 命令对以下内容很有用 −
The ping command is useful for the following −
-
Tracking and isolating hardware and software problems.
-
Determining the status of the network and various foreign hosts.
-
Testing, measuring, and managing networks.
Syntax
以下是使用 ftp 命令的简单语法 −
Following is the simple syntax to use the ftp command −
$ping hostname or ip-address
上述命令在每秒之后开始打印响应。要退出命令,您可以按 CNTRL + C 键来终止命令。
The above command starts printing a response after every second. To come out of the command, you can terminate it by pressing CNTRL + C keys.
Example
以下是一个检查网络上可用的主机是否可用的示例 −
Following is an example to check the availability of a host available on the network −
$ping google.com
PING google.com (74.125.67.100) 56(84) bytes of data.
64 bytes from 74.125.67.100: icmp_seq = 1 ttl = 54 time = 39.4 ms
64 bytes from 74.125.67.100: icmp_seq = 2 ttl = 54 time = 39.9 ms
64 bytes from 74.125.67.100: icmp_seq = 3 ttl = 54 time = 39.3 ms
64 bytes from 74.125.67.100: icmp_seq = 4 ttl = 54 time = 39.1 ms
64 bytes from 74.125.67.100: icmp_seq = 5 ttl = 54 time = 38.8 ms
--- google.com ping statistics ---
22 packets transmitted, 22 received, 0% packet loss, time 21017ms
rtt min/avg/max/mdev = 38.867/39.334/39.900/0.396 ms
$
如果主机不存在,您将收到以下输出 −
If a host does not exist, you will receive the following output −
$ping giiiiiigle.com
ping: unknown host giiiiigle.com
$
The ftp Utility
这里 ftp 代表 文件传输协议。此实用程序可帮助您将文件从一台计算机上载或下载到另一台计算机。
Here, ftp stands for *F*ile *T*ransfer *P*rotocol. This utility helps you upload and download your file from one computer to another computer.
ftp 实用程序有自己的一组类 Unix 命令。这些命令可帮助您执行以下任务 −
The ftp utility has its own set of Unix-like commands. These commands help you perform tasks such as −
-
Connect and login to a remote host.
-
Navigate directories.
-
List directory contents.
-
Put and get files.
-
Transfer files as ascii, ebcdic or binary.
Syntax
以下是使用 ftp 命令的简单语法 −
Following is the simple syntax to use the ftp command −
$ftp hostname or ip-address
上述命令将提示您输入登录 ID 和密码。一旦通过身份验证,您便可以访问登录帐户的主目录,并能够执行多种命令。
The above command would prompt you for the login ID and the password. Once you are authenticated, you can access the home directory of the login account and you would be able to perform various commands.
下表列出了几个重要命令 −
The following tables lists out a few important commands −
Sr.No. |
Command & Description |
1 |
put filename Uploads filename from the local machine to the remote machine. |
2 |
get filename Downloads filename from the remote machine to the local machine. |
3 |
mput file list Uploads more than one file from the local machine to the remote machine. |
4 |
mget file list Downloads more than one file from the remote machine to the local machine. |
5 |
prompt off Turns the prompt off. By default, you will receive a prompt to upload or download files using mput or mget commands. |
6 |
prompt on Turns the prompt on. |
7 |
dir Lists all the files available in the current directory of the remote machine. |
8 |
cd dirname Changes directory to dirname on the remote machine. |
9 |
lcd dirname Changes directory to dirname on the local machine. |
10 |
quit Helps logout from the current login. |
应该注意的是,所有文件都将下载或上传到当前目录或从当前目录下载或上传。如果您想要将文件上传到特定目录,则需要首先切换到该目录,然后再上传所需的文件。
It should be noted that all the files would be downloaded or uploaded to or from the current directories. If you want to upload your files in a particular directory, you need to first change to that directory and then upload the required files.
Example
下面是显示一些命令的工作原理的示例 −
Following is the example to show the working of a few commands −
$ftp amrood.com
Connected to amrood.com.
220 amrood.com FTP server (Ver 4.9 Thu Sep 2 20:35:07 CDT 2009)
Name (amrood.com:amrood): amrood
331 Password required for amrood.
Password:
230 User amrood logged in.
ftp> dir
200 PORT command successful.
150 Opening data connection for /bin/ls.
total 1464
drwxr-sr-x 3 amrood group 1024 Mar 11 20:04 Mail
drwxr-sr-x 2 amrood group 1536 Mar 3 18:07 Misc
drwxr-sr-x 5 amrood group 512 Dec 7 10:59 OldStuff
drwxr-sr-x 2 amrood group 1024 Mar 11 15:24 bin
drwxr-sr-x 5 amrood group 3072 Mar 13 16:10 mpl
-rw-r--r-- 1 amrood group 209671 Mar 15 10:57 myfile.out
drwxr-sr-x 3 amrood group 512 Jan 5 13:32 public
drwxr-sr-x 3 amrood group 512 Feb 10 10:17 pvm3
226 Transfer complete.
ftp> cd mpl
250 CWD command successful.
ftp> dir
200 PORT command successful.
150 Opening data connection for /bin/ls.
total 7320
-rw-r--r-- 1 amrood group 1630 Aug 8 1994 dboard.f
-rw-r----- 1 amrood group 4340 Jul 17 1994 vttest.c
-rwxr-xr-x 1 amrood group 525574 Feb 15 11:52 wave_shift
-rw-r--r-- 1 amrood group 1648 Aug 5 1994 wide.list
-rwxr-xr-x 1 amrood group 4019 Feb 14 16:26 fix.c
226 Transfer complete.
ftp> get wave_shift
200 PORT command successful.
150 Opening data connection for wave_shift (525574 bytes).
226 Transfer complete.
528454 bytes received in 1.296 seconds (398.1 Kbytes/s)
ftp> quit
221 Goodbye.
$
The telnet Utility
有时候我们需要连接到远程 Unix 计算机并在该计算机上远程工作。 Telnet 是一个实用程序,允许某个位置的计算机用户建立连接、登录,然后在另一位置的计算机上工作。
There are times when we are required to connect to a remote Unix machine and work on that machine remotely. Telnet is a utility that allows a computer user at one site to make a connection, login and then conduct work on a computer at another site.
使用 Telnet 登录后,您可以在远程连接的计算机上执行所有活动。以下是 Telnet 会话示例 −
Once you login using Telnet, you can perform all the activities on your remotely connected machine. The following is an example of Telnet session −
C:>telnet amrood.com
Trying...
Connected to amrood.com.
Escape character is '^]'.
login: amrood
amrood's Password:
*****************************************************
* *
* *
* WELCOME TO AMROOD.COM *
* *
* *
*****************************************************
Last unsuccessful login: Fri Mar 3 12:01:09 IST 2009
Last login: Wed Mar 8 18:33:27 IST 2009 on pts/10
{ do your work }
$ logout
Connection closed.
C:>
The finger Utility
finger 命令显示关于指定主机上用户的信息。该主机可以是本地或远程主机。
The finger command displays information about users on a given host. The host can be either local or remote.
由于安全原因,其他系统上的 Finger 命令可能被禁用。
Finger may be disabled on other systems for security reasons.
以下是使用 finger 命令的简单语法 −
Following is the simple syntax to use the finger command −
查看本地计算机上所有已登录的用户 −
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
获取本地计算机上特定可用用户的详细信息 −
Get information about a specific user available on the local machine −
$ finger amrood
Login: amrood Name: (null)
Directory: /home/amrood Shell: /bin/bash
On since Thu Jun 25 08:03 (MST) on pts/0 from 62.61.164.115
No mail.
No Plan.
查看远程计算机上所有已登录的用户 −
Check all the logged-in users on the remote machine −
$ finger @avtar.com
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
获取远程计算机上特定可用用户的详细信息 −
Get the information about a specific user available on the remote machine −
$ finger amrood@avtar.com
Login: amrood Name: (null)
Directory: /home/amrood Shell: /bin/bash
On since Thu Jun 25 08:03 (MST) on pts/0 from 62.61.164.115
No mail.
No Plan.
Unix - The vi Editor Tutorial
在本章中,我们将了解 vi 编辑器在 Unix 中如何工作。在 Unix 中有许多方法可以编辑文件。使用面向屏幕的文本编辑器 vi 编辑文件是最好的方法之一。此编辑器使您能够在与文件中其他行同上下文中编辑行。
In this chapter, we will understand how the vi Editor works in Unix. There are many ways to edit files in Unix. Editing files using the screen-oriented text editor vi is one of the best ways. This editor enables you to edit lines in context with other lines in the file.
现在还推出了一个名为 VIM 的 vi 编辑器的改进版本。在此,VIM 代表 *Vi IM*proved。
An improved version of the vi editor which is called the VIM has also been made available now. Here, VIM stands for *Vi IM*proved.
vi 通常被认为是 Unix 编辑器的实际标准,因为 −
vi is generally considered the de facto standard in Unix editors because −
-
It’s usually available on all the flavors of Unix system.
-
Its implementations are very similar across the board.
-
It requires very few resources.
-
It is more user-friendly than other editors such as the ed or the ex.
您可以使用 vi 编辑器编辑现有文件或从头开始创建新文件。您还可以使用此编辑器来仅读取文本文件。
You can use the vi editor to edit an existing file or to create a new file from scratch. You can also use this editor to just read a text file.
Starting the vi Editor
下表列出了 vi 编辑器的基本命令 −
The following table lists out the basic commands to use the vi editor −
Sr.No. |
Command & Description |
1 |
vi filename Creates a new file if it already does not exist, otherwise opens an existing file. |
2 |
vi -R filename Opens an existing file in the read-only mode. |
3 |
view filename Opens an existing file in the read-only mode. |
以下是创建新文件 testfile 的示例(如果当前工作目录中尚不存在) −
Following is an example to create a new file testfile if it already does not exist in the current working directory −
$vi testfile
上述命令将生成以下输出 −
The above command will generate the following output −
|
~
~
~
~
~
~
~
~
~
~
~
~
"testfile" [New File]
您会注意到光标后每一行上都有一个 tilde (~)。波浪线表示未使用的行。如果一行不以波浪线开头并且看起来是空白的,则那里有一个空格、制表符、换行符或其他不可查看的字符。
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused line. If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline, or some other non-viewable character present.
现在您有一个可供开始处理的打开文件。在进一步处理之前,让我们了解一些重要概念。
You now have one open file to start working on. Before proceeding further, let us understand a few important concepts.
Operation Modes
使用 vi 编辑器时,我们通常会遇到以下两种模式 −
While working with the vi editor, we usually come across the following two modes −
-
Command mode − This mode enables you to perform administrative tasks such as saving the files, executing the commands, moving the cursor, cutting (yanking) and pasting the lines or words, as well as finding and replacing. In this mode, whatever you type is interpreted as a command.
-
Insert mode − This mode enables you to insert text into the file. Everything that’s typed in this mode is interpreted as input and placed in the file.
vi 始终从 command mode 开始。要输入文本,您必须处于仅需键入 i 即可进入的插入模式。要退出插入模式,请按 Esc 键,该键将使您返回命令模式。
vi always starts in the command mode. To enter text, you must be in the insert mode for which simply type i. To come out of the insert mode, press the Esc key, which will take you back to the command mode.
Hint - 如果您不确定自己处于哪种模式,请按两次 Esc 键;这将使您进入命令模式。您使用 vi 编辑器打开一个文件。首先键入一些字符,然后再进入命令模式以了解其差别。
Hint − If you are not sure which mode you are in, press the Esc key twice; this will take you to the command mode. You open a file using the vi editor. Start by typing some characters and then come to the command mode to understand the difference.
Getting Out of vi
退出 vi 的命令为 :q 。进入命令模式后,键入冒号、“q”,然后按回车。如果文件以任何方式被修改,编辑器将警告您,并且不允许您退出。要忽略此消息,退出 vi 而不用保存的命令为 :q! 。这使您可以退出 vi,而不保存任何更改。
The command to quit out of vi is :q. Once in the command mode, type colon, and 'q', followed by return. If your file has been modified in any way, the editor will warn you of this, and not let you quit. To ignore this message, the command to quit out of vi without saving is :q!. This lets you exit vi without saving any of the changes.
保存编辑器内容的命令为 :w 。您可以将以上命令与退出命令结合使用,或者使用 :wq 并回车。
The command to save the contents of the editor is :w. You can combine the above command with the quit command, or use :wq and return.
最简单的方法是使用 ZZ 命令 save your changes and exit vi 。当您处于命令模式时,键入 ZZ 。 ZZ 命令的操作方式与 :wq 命令相同。
The easiest way to save your changes and exit vi is with the ZZ command. When you are in the command mode, type ZZ. The ZZ command works the same way as the :wq command.
如果想要指定/说明文件的任何特定名称,可以通过 :w 后指定该名称。例如,如果您想要将您正在处理的文件保存为以 filename2 为名的另一个文件名,您将键入 :w filename2 并回车。
If you want to specify/state any particular name for the file, you can do so by specifying it after the :w. For example, if you wanted to save the file you were working on as another filename called filename2, you would type :w filename2 and return.
Moving within a File
要在不影响文本的情况下在一个文件中四处移动,您必须处于命令模式(按两次 Esc)。下表列出了一些可供您逐个字符移动的命令 −
To move around within a file without affecting your text, you must be in the command mode (press Esc twice). The following table lists out a few commands you can use to move around one character at a time −
Sr.No. |
Command & Description |
1 |
k Moves the cursor up one line |
2 |
j Moves the cursor down one line |
3 |
h Moves the cursor to the left one character position |
4 |
l Moves the cursor to the right one character position |
在文件中移动需要考虑以下几点 −
The following points need to be considered to move within a file −
-
vi is case-sensitive. You need to pay attention to capitalization when using the commands.
-
Most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2j moves the cursor two lines down the cursor location.
vi 中还有许多其他方法可以在文件中移动。请记住,您必须处于命令模式 ( press Esc twice )。下表列出了一些在文件中四处移动的命令 −
There are many other ways to move within a file in vi. Remember that you must be in the command mode (press Esc twice). The following table lists out a few commands to move around the file −
Control Commands
在表中给出了使用控制键执行相应功能的命令:
The following commands can be used with the Control Key to performs functions as given in the table below −
Editing Files
要编辑该文件,您需要进入插入模式。有许多方法可从命令模式进入插入模式:
To edit the file, you need to be in the insert mode. There are many ways to enter the insert mode from the command mode −
Sr.No. |
Command & Description |
1 |
i Inserts text before the current cursor location |
2 |
I Inserts text at the beginning of the current line |
3 |
a Inserts text after the current cursor location |
4 |
A Inserts text at the end of the current line |
5 |
o Creates a new line for text entry below the cursor location |
6 |
O Creates a new line for text entry above the cursor location |
Deleting Characters
这里列出了用于删除打开文件中的字符和行的重要命令:
Here is a list of important commands, which can be used to delete characters and lines in an open file −
Sr.No. |
Command & Description |
1 |
x Deletes the character under the cursor location |
2 |
X Deletes the character before the cursor location |
3 |
dw Deletes from the current cursor location to the next word |
4 |
d^ Deletes from the current cursor position to the beginning of the line |
5 |
d$ Deletes from the current cursor position to the end of the line |
6 |
D Deletes from the cursor position to the end of the current line |
7 |
dd Deletes the line the cursor is on |
如上所述,vi 中的大多数命令均可以有该操作发生的次数作为前置条件。例如, 2x 删除光标位置下的两个字符, 2dd 删除光标所在的两个行。
As mentioned above, most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2x deletes two characters under the cursor location and 2dd deletes two lines the cursor is on.
建议在继续之前练习这些命令。
It is recommended that the commands are practiced before we proceed further.
Change Commands
您还可以更改字符、单词或 vi 中的行,而不删除它们。相关命令如下:
You also have the capability to change characters, words, or lines in vi without deleting them. Here are the relevant commands −
Sr.No. |
Command & Description |
1 |
cc Removes the contents of the line, leaving you in insert mode. |
2 |
cw Changes the word the cursor is on from the cursor to the lowercase w end of the word. |
3 |
r Replaces the character under the cursor. vi returns to the command mode after the replacement is entered. |
4 |
R Overwrites multiple characters beginning with the character currently under the cursor. You must use Esc to stop the overwriting. |
5 |
s Replaces the current character with the character you type. Afterward, you are left in the insert mode. |
6 |
S Deletes the line the cursor is on and replaces it with the new text. After the new text is entered, vi remains in the insert mode. |
Copy and Paste Commands
您可以从一个地方复制行或单词,然后使用以下命令将它们粘贴到另一个地方 −
You can copy lines or words from one place and then you can paste them at another place using the following commands −
Sr.No. |
Command & Description |
1 |
yy Copies the current line. |
2 |
yw Copies the current word from the character the lowercase w cursor is on, until the end of the word. |
3 |
p Puts the copied text after the cursor. |
4 |
P Puts the yanked text before the cursor. |
Advanced Commands
有一些高级命令可以简化日常编辑并更有效地使用 vi −
There are some advanced commands that simplify day-to-day editing and allow for more efficient use of vi −
Word and Character Searching
vi 编辑器有两种搜索: string 和 character 。对于字符串搜索,使用 / 和 ? 命令。当您启动这些命令时,刚刚键入的命令将显示在屏幕的最后一行,您可以在其中键入要查找的特定字符串。
The vi editor has two kinds of searches: string and character. For a string search, the / and ? commands are used. When you start these commands, the command just typed will be shown on the last line of the screen, where you type the particular string to look for.
这两个命令仅在搜索发生的方向上有所不同 −
These two commands differ only in the direction where the search takes place −
-
The / command searches forwards (downwards) in the file.
-
The ? command searches backwards (upwards) in the file.
n 和 N 命令分别在相同或相反的方向重复先前的搜索命令。一些字符具有特殊含义。这些字符之前必须加反斜杠 ( \ ) 才能作为搜索表达式的组成部分。
The n and N commands repeat the previous search command in the same or the opposite direction, respectively. Some characters have special meanings. These characters must be preceded by a backslash (\) to be included as part of the search expression.
Sr.No. |
Character &Description |
1 |
^ Searches at the beginning of the line (Use at the beginning of a search expression). |
2 |
. Matches a single character. |
3 |
* Matches zero or more of the previous character. |
4 |
$ End of the line (Use at the end of the search expression). |
5 |
[ Starts a set of matching or non-matching expressions. |
6 |
< This is put in an expression escaped with the backslash to find the ending or the beginning of a word. |
7 |
> This helps see the '<' character description above. |
字符搜索在单行内进行,用于找到命令后输入的字符。 f 和 F 命令仅在当前行中搜索字符。 f 向前搜索, F 向后搜索,光标移动到找到的字符位置。
The character search searches within one line to find a character entered after the command. The f and F commands search for a character on the current line only. f searches forwards and F searches backwards and the cursor moves to the position of the found character.
t 和 T 命令仅在当前行中搜索字符,但对于 t ,光标移动到字符前面的位置,而 T 向后搜索整行直到字符的后面位置。
The t and T commands search for a character on the current line only, but for t, the cursor moves to the position before the character, and T searches the line backwards to the position after the character.
Set Commands
您可以使用以下 :set 命令来更改 vi 屏幕的外观。在命令模式后,键入 :set ,再输入下述任意命令。
You can change the look and feel of your vi screen using the following :set commands. Once you are in the command mode, type :set followed by any of the following commands.
Sr.No. |
Command & Description |
1 |
:set ic Ignores the case when searching |
2 |
:set ai Sets autoindent |
3 |
:set noai Unsets autoindent |
4 |
:set nu Displays lines with line numbers on the left side |
5 |
:set sw Sets the width of a software tabstop. For example, you would set a shift width of 4 with this command — :set sw = 4 |
6 |
:set ws If wrapscan is set, and the word is not found at the bottom of the file, it will try searching for it at the beginning |
7 |
:set wm If this option has a value greater than zero, the editor will automatically "word wrap". For example, to set the wrap margin to two characters, you would type this: :set wm = 2 |
8 |
:set ro Changes file type to "read only" |
9 |
:set term Prints terminal type |
10 |
:set bf Discards control characters from input |
Running Commands
vi 有能力在编辑器内运行命令。要运行命令,您只需进入命令模式并输入 :! 命令。
The vi has the capability to run commands from within the editor. To run a command, you only need to go to the command mode and type :! command.
例如,如果您希望在尝试使用该文件名保存文件之前检查是否存在文件,您可以键入 :! ls ,您将在屏幕上看到 ls 的输出。
For example, if you want to check whether a file exists before you try to save your file with that filename, you can type :! ls and you will see the output of ls on the screen.
您可以按任意键(或命令的转义序列)返回到 vi 会话。
You can press any key (or the command’s escape sequence) to return to your vi session.
Replacing Text
替换命令 ( :s/ ) 使您可以快速替换文件中的单词或单词组。以下是替换文本的语法 -
The substitution command (:s/) enables you to quickly replace words or groups of words within your files. Following is the syntax to replace text −
:s/search/replace/g
g 表示全局。此命令的结果是光标行上的所有出现的单词均发生改变。
The g stands for globally. The result of this command is that all occurrences on the cursor’s line are changed.
Important Points to Note
下列要点将让您使用 vi 更加成功 -
The following points will add to your success with vi −
-
You must be in command mode to use the commands. (Press Esc twice at any time to ensure that you are in command mode.)
-
You must be careful with the commands. These are case-sensitive.
-
You must be in insert mode to enter text.
Unix - What is Shells?
Shell 为您提供了 Unix 系统的接口。它会从您处收集输入,并根据该输入执行程序。当一个程序完成执行时,它会显示该程序的输出。
A Shell provides you with an interface to the Unix system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program’s output.
Shell 是一个环境,我们可以在其中运行我们的命令、程序和 shell 脚本。Shell 有不同的类型,就像操作系统有不同的类型一样。每种类型的 shell 都有一组自己识别的命令和功能。
Shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of a shell, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized commands and functions.
Shell Prompt
提示符 $ (称为 command prompt )是由 shell 发出的。在提示符显示时,您可以键入一个命令。
The prompt, $, which is called the command prompt, is issued by the shell. While the prompt is displayed, you can type a command.
在您按下 Enter 后,Shell 会读取您的输入。它通过查看您的输入的第一个单词来确定您想要执行的命令。一个单词是一组不间断的字符。空格和制表符用于分隔单词。
Shell reads your input after you press Enter. It determines the command you want executed by looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs separate words.
以下是一个 date 命令的简单示例,该命令显示当前日期和时间 −
Following is a simple example of the date command, which displays the current date and time −
$date
Thu Jun 25 08:30:19 MST 2009
您可以使用环境教程中说明的环境变量 PS1 来自定义您的命令提示符。
You can customize your command prompt using the environment variable PS1 explained in the Environment tutorial.
Shell Types
在 Unix 中,主要有两种类型的 shell −
In Unix, there are two major types of shells −
-
Bourne shell − If you are using a Bourne-type shell, the $ character is the default prompt.
-
C shell − If you are using a C-type shell, the % character is the default prompt.
Bourne Shell 有以下子类别 −
The Bourne Shell has the following subcategories −
-
Bourne shell (sh)
-
Korn shell (ksh)
-
Bourne Again shell (bash)
-
POSIX shell (sh)
各种 C 型 shell 如下 −
The different C-type shells follow −
-
C shell (csh)
-
TENEX/TOPS C shell (tcsh)
最初的 Unix shell 是由斯蒂芬·R·伯恩在 20 世纪 70 年代中期编写,当时他在新泽西的 AT&T 贝尔实验室工作。
The original Unix shell was written in the mid-1970s by Stephen R. Bourne while he was at the AT&T Bell Labs in New Jersey.
Bourne Shell 是第一个出现在 Unix 系统上的 shell,因此它被称为“shell”。
Bourne shell was the first shell to appear on Unix systems, thus it is referred to as "the shell".
Bourne Shell 通常安装为 /bin/sh ,用于大多数版本的 Unix。出于此原因,对于编写可以在不同版本的 Unix 上使用的脚本,它是首选 shell。
Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is the shell of choice for writing scripts that can be used on different versions of Unix.
在本章中,我们将介绍基于 Borne Shell 的大多数 Shell 概念。
In this chapter, we are going to cover most of the Shell concepts that are based on the Borne Shell.
Shell Scripts
shell 脚本的基本概念是命令列表,这些命令按执行顺序列出。一个好的 shell 脚本将有注释,在前面加 # 符号,描述步骤。
The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by # sign, describing the steps.
有条件测试,例如值 A 大于值 B,循环允许我们遍历海量数据、文件来读取和存储数据,以及读取和存储数据的变量,并且该脚本可能包含函数。
There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive amounts of data, files to read and store data, and variables to read and store data, and the script may include functions.
我们将在下一节中编写许多脚本。它将是一个简单的文本文件,其中我们将放置所有命令和大量其他所需结构,告诉 shell 环境做什么以及何时执行。
We are going to write many scripts in the next sections. It would be a simple text file in which we would put all our commands and several other required constructs that tell the shell environment what to do and when to do it.
Shell 脚本和函数都经过解释。这意味着它们未被编译。
Shell scripts and functions are both interpreted. This means they are not compiled.
Example Script
假设我们创建一个 test.sh 脚本。请注意,所有脚本都应具有 .sh 扩展名。在向脚本添加任何其他内容之前,您需要提醒系统正在启动 shell 脚本。使用 shebang 构造完成此操作。例如 −
Assume we create a test.sh script. Note all the scripts would have the .sh extension. Before you add anything else to your script, you need to alert the system that a shell script is being started. This is done using the shebang construct. For example −
#!/bin/sh
这告诉系统后续命令将由 Bourne Shell 执行。它被称为 Shebang,因为 # 符号称为井号,而 ! 符号称为惊叹号。
This tells the system that the commands that follow are to be executed by the Bourne shell. It’s called a shebang because the # symbol is called a hash, and the ! symbol is called a bang.
要在包含这些命令的脚本中,您首先放置 Shebang 行,然后再添加命令 −
To create a script containing these commands, you put the shebang line first and then add the commands −
#!/bin/bash
pwd
ls
Shell Comments
您可以按如下方式将注释放入脚本中 −
You can put your comments in your script as follows −
#!/bin/bash
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
pwd
ls
保存上述内容并使脚本可执行 −
Save the above content and make the script executable −
$chmod +x test.sh
Shell 脚本现在可以执行 −
The shell script is now ready to be executed −
$./test.sh
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
/home/amrood
index.htm unix-basic_utilities.htm unix-directories.htm
test.sh unix-communication.htm unix-environment.htm
Note − 要执行当前目录中可用的程序,请使用 ./program_name
Note − To execute a program available in the current directory, use ./program_name
Extended Shell Scripts
Shell 脚本有几个必需的构造,告诉 shell 环境做什么以及何时执行它。当然,大多数脚本都比上述脚本更复杂。
Shell scripts have several required constructs that tell the shell environment what to do and when to do it. Of course, most scripts are more complex than the above one.
Shell 毕竟是一种真正的编程语言,具有变量、控制结构等。无论脚本多复杂,它仍然只是一个按顺序执行的命令列表。
The shell is, after all, a real programming language, complete with variables, control structures, and so forth. No matter how complicated a script gets, it is still just a list of commands executed sequentially.
以下脚本使用 read 命令,该命令从键盘获取输入并将其分配为 PERSON 变量的值,最后将其打印到 STDOUT。
The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
以下是脚本的一个示例运行 −
Here is a sample run of the script −
$./test.sh
What is your name?
Zara Ali
Hello, Zara Ali
$
Unix - Using Shell Variables
在本章中,我们将学习如何在 Unix 中使用 Shell 变量。变量是一个字符字符串,我们为其分配一个值。分配的值可以是数字、文本、文件名、设备或任何其他类型的数据。
In this chapter, we will learn how to use Shell variables in Unix. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.
变量不过是实际数据的指针。shell 允许你创建、分配和删除变量。
A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.
Variable Names
变量的名称只能包含字母(a 到 z 或 A 到 Z)、数字(0 到 9)或下划线字符(_)。
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).
根据惯例,Unix shell 变量的名称使用大写。
By convention, Unix shell variables will have their names in UPPERCASE.
以下示例是有效的变量名称 −
The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2
以下是无效变量名称的示例 −
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
你无法使用 ! 、 * 或 - 等其他字符的原因是,这些字符对 shell 具有特殊含义。
The reason you cannot use other characters such as !, *, or - is that these characters have a special meaning for the shell.
Defining Variables
变量的定义如下 −
Variables are defined as follows −
variable_name=variable_value
例如 -
For example −
NAME="Zara Ali"
以上示例定义了变量 NAME 并为其分配值 "Zara Ali"。此类型的变量称为 scalar variables 。标量变量一次只能保存一个值。
The above example defines the variable NAME and assigns the value "Zara Ali" to it. Variables of this type are called scalar variables. A scalar variable can hold only one value at a time.
Shell 允许你将任何值存储在变量中。例如 −
Shell enables you to store any value you want in a variable. For example −
VAR1="Zara Ali"
VAR2=100
Accessing Values
要访问存储在变量中的值,请在其名称前加上美元符号 ( $ ) −
To access the value stored in a variable, prefix its name with the dollar sign ($) −
例如,以下脚本将访问定义的变量 NAME 的值并将其打印到 STDOUT −
For example, the following script will access the value of defined variable NAME and print it on STDOUT −
#!/bin/sh
NAME="Zara Ali"
echo $NAME
以上脚本将生成以下值 −
The above script will produce the following value −
Zara Ali
Read-only Variables
Shell 通过使用只读命令提供了一种将变量标记为只读的方法。变量标记为只读后,其值无法更改。
Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed.
例如,以下脚本在尝试更改 NAME 的值时生成错误 −
For example, the following script generates an error while trying to change the value of NAME −
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
上述脚本会生成以下结果 -
The above script will generate the following result −
/bin/sh: NAME: This variable is read only.
Unsetting Variables
取消或删除变量会指示 shell 从其跟踪的变量列表中删除该变量。取消变量后,你将无法访问变量中存储的值。
Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable.
以下是使用 unset 命令取消已定义变量的语法 −
Following is the syntax to unset a defined variable using the unset command −
unset variable_name
以上命令取消已定义变量的值。以下是一个简单的示例,演示了该命令如何工作 −
The above command unsets the value of a defined variable. Here is a simple example that demonstrates how the command works −
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME
以上示例不打印任何内容。你无法使用 unset 命令取消标记为 readonly 的 unset 变量。
The above example does not print anything. You cannot use the unset command to unset variables that are marked readonly.
Variable Types
当 shell 运行时,存在三种主要类型的变量 −
When a shell is running, three main types of variables are present −
-
Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt.
-
Environment Variables − An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually, a shell script defines only those environment variables that are needed by the programs that it runs.
-
Shell Variables − A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.
Unix - Special Variables
在本章中,我们将详细讨论 Unix 中的特殊变量。在以前的章节中,我们已经了解了在变量名中使用某些非字母数字字符时的注意事项。这是因为这些字符用于 Unix 特殊变量的名称中。这些变量是为特定函数保留的。
In this chapter, we will discuss in detail about special variable in Unix. In one of our previous chapters, we understood how to be careful when we use certain nonalphanumeric characters in variable names. This is because those characters are used in the names of special Unix variables. These variables are reserved for specific functions.
例如,字符 $ 表示当前 shell 的进程 ID 号或 PID −
For example, the $ character represents the process ID number, or PID, of the current shell −
$echo $$
以上命令会写入当前 shell 的 PID −
The above command writes the PID of the current shell −
29949
下表显示了可以在 shell 脚本中使用的许多特殊变量 −
The following table shows a number of special variables that you can use in your shell scripts −
Sr.No. |
Variable & Description |
1 |
$0 The filename of the current script. |
2 |
$n These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on). |
3 |
$# The number of arguments supplied to a script. |
4 |
$* All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2. |
5 |
$@ All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2. |
6 |
$? The exit status of the last command executed. |
7 |
$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing. |
8 |
$! The process number of the last background command. |
Command-Line Arguments
命令行参数 $1、$2、$3、…$9 是位置参数,其中 $0 指向实际命令、程序、shell 脚本或函数,$1、$2、$3、…$9 作为指令的参数。
The command-line arguments $1, $2, $3, …$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, …$9 as the arguments to the command.
以下脚本使用与命令行相关的各种特殊变量 −
Following script uses various special variables related to the command line −
#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
下面是上述脚本的一个运行示例——
Here is a sample run for the above script −
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
Special Parameters $* and $@
有特殊的参数允许一次访问所有命令行参数。 $ * 和 $@ 二者扮演同样的角色,除非它们被包含在双引号中, "" 。
There are special parameters that allow accessing all the command-line arguments at once. $* and $@ both will act the same unless they are enclosed in double quotes, "".
这两个参数都指定了命令行参数。但是,"$*" 特殊参数将整个列表作为一个参数,参数之间有空格,而 "$@" 特殊参数将整个列表分解为单独的参数。
Both the parameters specify the command-line arguments. However, the "$*" special parameter takes the entire list as one argument with spaces between and the "$@" special parameter takes the entire list and separates it into separate arguments.
我们可以编写如下所示的 shell 脚本以使用 $* 或 $@ 特殊参数处理任意数量的命令行参数——
We can write the shell script as shown below to process an unknown number of commandline arguments with either the $* or $@ special parameters −
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
下面是上述脚本的一个运行示例——
Here is a sample run for the above script −
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old
Note ——此处 do…done 是将涵盖在后续教程中的某种循环。
Note − Here do…done is a kind of loop that will be covered in a subsequent tutorial.
Exit Status
$? 变量表示上一个命令的退出状态。
The $? variable represents the exit status of the previous command.
退出状态是在命令执行完毕后返回的数值。按照规则,大多数命令如果成功会返回退出状态 0,如果失败会返回 1。
Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.
有些命令会出于特定原因返回其他退出状态。例如,有些命令会区分不同类型的错误,并会根据特定类型的错误而返回不同的退出值。
Some commands return additional exit statuses for particular reasons. For example, some commands differentiate between kinds of errors and will return various exit values depending on the specific type of failure.
以下是成功命令的示例——
Following is the example of successful command −
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
$echo $?
0
$
Unix - Using Shell Arrays
在本章中,我们将讨论如何在 Unix 中使用 shell 数组。shell 变量有足够的能力来保存单个值。这些变量称为标量变量。
In this chapter, we will discuss how to use shell arrays in Unix. A shell variable is capable enough to hold a single value. These variables are called scalar variables.
Shell 支持一种不同的变量类型,称为 array variable 。这可以同时保存多个值。数组提供了一种对变量集合进行分组的方法。你可以使用一个保存所有其他变量的单一数组变量,而不必为每个必需的变量创建一个新名称。
Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables.
为命名数组时,所有讨论过的 Shell 变量的命名规则均适用。
All the naming rules discussed for Shell Variables would be applicable while naming arrays.
Defining Array Values
数组变量和标量变量之间的差异可以解释如下。
The difference between an array variable and a scalar variable can be explained as follows.
假设你要将各种学生的姓名表示为一组变量。每个单独变量都是一个标量变量,如下所示 –
Suppose you are trying to represent the names of various students as a set of variables. Each of the individual variables is a scalar variable as follows −
NAME01="Zara"
NAME02="Qadir"
NAME03="Mahnaz"
NAME04="Ayan"
NAME05="Daisy"
我们可以使用一个单独的数组来存储所有上面提到的姓名。以下是创建数组变量的最简单方法。这有助于将其一个索引值分配给其一个索引。
We can use a single array to store all the above mentioned names. Following is the simplest method of creating an array variable. This helps assign a value to one of its indices.
array_name[index]=value
此处,array_name 是数组的名称,index 是你要设置的数组中该项的索引,而 value 是你要为该项设置的值。
Here array_name is the name of the array, index is the index of the item in the array that you want to set, and value is the value you want to set for that item.
例如,以下命令 –
As an example, the following commands −
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
如果你使用的是 ksh shell,则以下为数组初始化的语法 –
If you are using the ksh shell, here is the syntax of array initialization −
set -A array_name value1 value2 ... valuen
如果你使用的是 bash shell,则以下为数组初始化的语法 –
If you are using the bash shell, here is the syntax of array initialization −
array_name=(value1 ... valuen)
Accessing Array Values
在你设置任何数组变量后,访问方式如下 –
After you have set any array variable, you access it as follows −
${array_name[index]}
此处,array_name 是数组的名称,而 index 是要访问的值的索引。以下是一个了解这个概念的例子 –
Here array_name is the name of the array, and index is the index of the value to be accessed. Following is an example to understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
以上示例将生成以下结果 –
The above example will generate the following result −
$./test.sh
First Index: Zara
Second Index: Qadir
你可以使用以下其中一种方式访问数组中的所有项 –
You can access all the items in an array in one of the following ways −
${array_name[*]}
${array_name[@]}
此处 array_name 是您感兴趣的数组的名称。以下示例将帮助您理解该概念 -
Here array_name is the name of the array you are interested in. Following example will help you understand the concept −
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
以上示例将生成以下结果 –
The above example will generate the following result −
$./test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy
Unix - Shell Basic Operators
每个 shell 都支持各种运算符。我们将在本章详细讨论 Bourne shell(默认 shell)。
There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.
我们现在将讨论以下运算符 -
We will now discuss the following operators −
-
Arithmetic Operators
-
Relational Operators
-
Boolean Operators
-
String Operators
-
File Test Operators
Bourne shell 最初没有任何执行简单算术运算的机制,但它使用外部程序,要么是 awk ,要么是 expr 。
Bourne shell didn’t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.
以下示例显示了如何添加两个数字 -
The following example shows how to add two numbers −
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
上述脚本会生成以下结果 -
The above script will generate the following result −
Total value : 4
在添加时需要考虑以下几点 -
The following points need to be considered while adding −
-
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
-
The complete expression should be enclosed between ‘ ‘, called the backtick.
Arithmetic Operators
Bourne Shell 支持以下算术运算符。
The following arithmetic operators are supported by Bourne Shell.
假设变量 a 为 10,变量 b 为 20,那么 -
Assume variable a holds 10 and variable b holds 20 then −
Operator |
Description |
Example |
+ (Addition) |
Adds values on either side of the operator |
|
- (Subtraction) |
Subtracts right hand operand from left hand operand |
|
* (Multiplication) |
Multiplies values on either side of the operator |
|
/ (Division) |
Divides left hand operand by right hand operand |
|
% (Modulus) |
Divides left hand operand by right hand operand and returns remainder |
|
= (Assignment) |
Assigns right operand in left operand |
a = $b would assign value of b into a |
== (Equality) |
Compares two numbers, if both are same then returns true. |
[ $a == $b ] would return false. |
!= (Not Equality) |
Compares two numbers, if both are different then returns true. |
[ $a != $b ] would return true. |
了解到所有条件表达式都应位于带空格的方括号当中非常重要,例如 [ $a == $b ] 是正确的,而 [$a==$b] 是不正确的。
It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
所有算术运算都使用长整数进行。
All the arithmetical calculations are done using long integers.
Relational Operators
Bourne Shell 支持以下特定于数值的关联运算符。这些运算符不适用于字符串值,除非其值为数值。
Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.
例如,以下运算符将用于检查 10 和 20 之间的关系以及 "10" 和 "20" 之间的关系,但不用于检查 "ten" 和 "twenty" 之间的关系。
For example, following operators will work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty".
假设变量 a 为 10,变量 b 为 20,那么 -
Assume variable a holds 10 and variable b holds 20 then −
Operator |
Description |
Example |
-eq |
Checks if the value of two operands are equal or not; if yes, then the condition becomes true. |
[ $a -eq $b ] is not true. |
-ne |
Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. |
[ $a -ne $b ] is true. |
-gt |
Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. |
[ $a -gt $b ] is not true. |
-lt |
Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. |
[ $a -lt $b ] is true. |
-ge |
Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. |
[ $a -ge $b ] is not true. |
-le |
Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. |
[ $a -le $b ] is true. |
了解所有条件表达式都应放在方括号中且周围带有空格非常重要。例如, [ $a ⇐ $b ] 正确,而 [$a ⇐ $b] 错误。
It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a ⇐ $b ] is correct whereas, [$a ⇐ $b] is incorrect.
Boolean Operators
Bourne Shell 支持以下布尔运算符。
The following Boolean operators are supported by the Bourne Shell.
假设变量 a 为 10,变量 b 为 20,那么 -
Assume variable a holds 10 and variable b holds 20 then −
Operator |
Description |
Example |
! |
This is logical negation. This inverts a true condition into false and vice versa. |
[ ! false ] is true. |
-o |
This is logical OR. If one of the operands is true, then the condition becomes true. |
[ $a -lt 20 -o $b -gt 100 ] is true. |
-a |
This is logical AND. If both the operands are true, then the condition becomes true otherwise false. |
[ $a -lt 20 -a $b -gt 100 ] is false. |
String Operators
Bourne Shell 支持以下字符串运算符。
The following string operators are supported by Bourne Shell.
假设 a 变量保存了“abc”, b 变量保存了“efg”,则 −
Assume variable a holds "abc" and variable b holds "efg" then −
Operator |
Description |
Example |
= |
Checks if the value of two operands are equal or not; if yes, then the condition becomes true. |
[ $a = $b ] is not true. |
!= |
Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true. |
[ $a != $b ] is true. |
-z |
Checks if the given string operand size is zero; if it is zero length, then it returns true. |
[ -z $a ] is not true. |
-n |
Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true. |
[ -n $a ] is not false. |
str |
Checks if str is not the empty string; if it is empty, then it returns false. |
[ $a ] is not false. |
File Test Operators
我们有几个运算符,可用于测试与 Unix 文件关联的各种属性。
We have a few operators that can be used to test various properties associated with a Unix file.
假设变量 file 保存现有文件名“test”,其大小为 100 字节,对 − 的权限为 read 、 write 和 execute
Assume a variable file holds an existing file name "test" the size of which is 100 bytes and has read, write and execute permission on −
Operator |
Description |
Example |
-b file |
Checks if file is a block special file; if yes, then the condition becomes true. |
[ -b $file ] is false. |
-c file |
Checks if file is a character special file; if yes, then the condition becomes true. |
[ -c $file ] is false. |
-d file |
Checks if file is a directory; if yes, then the condition becomes true. |
[ -d $file ] is not true. |
-f file |
Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true. |
[ -f $file ] is true. |
-g file |
Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true. |
[ -g $file ] is false. |
-k file |
Checks if file has its sticky bit set; if yes, then the condition becomes true. |
[ -k $file ] is false. |
-p file |
Checks if file is a named pipe; if yes, then the condition becomes true. |
[ -p $file ] is false. |
-t file |
Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true. |
[ -t $file ] is false. |
-u file |
Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true. |
[ -u $file ] is false. |
-r file |
Checks if file is readable; if yes, then the condition becomes true. |
[ -r $file ] is true. |
-w file |
Checks if file is writable; if yes, then the condition becomes true. |
[ -w $file ] is true. |
-x file |
Checks if file is executable; if yes, then the condition becomes true. |
[ -x $file ] is true. |
-s file |
Checks if file has size greater than 0; if yes, then condition becomes true. |
[ -s $file ] is true. |
-e file |
Checks if file exists; is true even if file is a directory but exists. |
[ -e $file ] is true. |
C Shell Operators
以下链接将给您简要了解 C Shell 算符−
Following link will give you a brief idea on C Shell Operators −
Unix - Shell Decision Making
在本章中,我们将了解 Unix 中的 shell 决策制定。在编写 shell 脚本时,可能会遇到需要在给定的两条路径中选择一条路径的情况。因此,您需要使用条件语句,让您的程序可以做出正确的决策并执行正确操作。
In this chapter, we will understand shell decision-making in Unix. While writing a shell script, there may be a situation when you need to adopt one path out of the given two paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform the right actions.
Unix Shell 支持条件语句,用于根据不同的条件执行不同的操作。现在,我们将了解此处的两个决策制定语句 −
Unix Shell supports conditional statements which are used to perform different actions based on different conditions. We will now understand two decision-making statements here −
-
The if…else statement
-
The case…esac statement
The if…else statements
if else 语句是有用的决策制定语句,可用于从给定的一组选项中选择一个选项。
If else statements are useful decision-making statements which can be used to select an option from a given set of options.
Unix Shell 支持以下 if…else 语句形式 −
Unix Shell supports following forms of if…else statement −
大多数 if 语句使用上一章中讨论的关系运算符来检查关系。
Most of the if statements check relations using relational operators discussed in the previous chapter.
The case…esac Statement
您可以使用多个 if…elif 语句执行多路分支。但是,这并不总是一种最佳解决方案,尤其是当所有分支都依赖于单个变量的值时。
You can use multiple if…elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Unix Shell 支持 case…esac 语句,该语句可以精确地处理这种情况,而且比重复的 if…elif 语句更高效。
Unix Shell supports case…esac statement which handles exactly this situation, and it does so more efficiently than repeated if…elif statements.
只有一种形式的 case…esac 语句,此处已对其进行了详细描述 −
There is only one form of case…esac statement which has been described in detail here −
Unix shell 中的 case…esac 语句与我们在其他编程语言中有的 switch…case 语句非常类似,例如 C 或 C++ 和 PERL 等。
The case…esac statement in the Unix shell is very similar to the switch…case statement we have in other programming languages like C or C++ and PERL, etc.
Unix - Shell Loop Types
在本章节中,我们将讨论 Unix 中的 shell 循环。循环是一个功能强大的编程工具,使您能够重复执行一组命令。在本章中,我们将检查 shell 编程人员可用的以下类型的循环−
In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −
根据具体情况,您将使用不同的循环。例如, while 循环会在给定条件保持真时执行给定的命令; until 循环会在给定条件变为真时执行。
You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.
一旦您有了良好的编程习惯,您将获得专业知识,因此,开始根据具体情况使用适当的循环。此处, while 和 for 循环在大多数其他编程语言中可用,如 C 、 C++ 和 PERL 等。
Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc.
Nesting Loops
所有循环都支持嵌套概念,这意味着您可以将一个循环放入另一个类似循环或不同循环中。根据您的要求,这种嵌套可以进行无限次。
All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement.
以下是一个嵌套 while 循环的示例。其他循环可以类似地根据编程要求进行嵌套−
Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −
Nesting while Loops
可以将一个 while 循环用作另一个 while 循环的主体的一部分。
It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
done
Example
这里有一个简单的循环嵌套示例。让我们在您用来计数到九的循环中添加另一个倒数循环−
Here is a simple example of loop nesting. Let’s add another countdown loop inside the loop that you used to count to nine −
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
这将产生以下结果。重要的是要注意 echo -n 在此处如何工作的。此处 -n 选项让 echo 避免打印一个新行字符。
This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
Unix - Shell Loop Control
在本章中,我们将讨论 Unix 中的 Shell 循环控制。迄今为止,您已了解如何创建循环并使用循环来完成不同任务。有时,您需要停止循环或跳过循环迭代。
In this chapter, we will discuss shell loop control in Unix. So far you have looked at creating loops and working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of the loop.
在本章中,我们将学习用于控制 Shell 循环的以下两个语句 −
In this chapter, we will learn following two statements that are used to control shell loops−
-
The break statement
-
The continue statement
The infinite Loop
所有循环都有一个有限的生命周期,并且根据循环的不同,当条件为假或真时,它们就会退出。
All the loops have a limited life and they come out once the condition is false or true depending on the loop.
如果未满足所需条件,则循环可能无限期地继续。无限期执行并且不会终止的循环将无限次执行。因此,这样的循环称为无限循环。
A loop may continue forever if the required condition is not met. A loop that executes forever without terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.
Example
下面是一个简单的示例,它使用 while 循环来显示数字 0 到 9 −
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=10
until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
此循环无限期地继续,因为 a 始终为 greater than 或 equal to 10 ,并且它永远不会小于 10。
This loop continues forever because a is always greater than or equal to 10 and it is never less than 10.
The break Statement
break 语句用于在执行到 break 语句的所有代码行后终止整个循环的执行。然后,它向下执行到循环结束后面的代码。
The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then steps down to the code following the end of the loop.
Syntax
以下 break 语句用于退出循环 −
The following break statement is used to come out of a loop −
break
break 命令还可以使用此格式从嵌套循环中退出 −
The break command can also be used to exit from a nested loop using this format −
break n
这里 n 指定了退出的 nth 循环。
Here n specifies the nth enclosing loop to the exit from.
Example
下面是一个简单的示例,它显示了当 a 变为 5 时循环如何终止 −
Here is a simple example which shows that loop terminates as soon as a becomes 5 −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
0
1
2
3
4
5
下面是嵌套 for 循环的一个简单示例。如果 var1 equals 2 和 var2 equals 0 −
Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and var2 equals 0 −
#!/bin/sh
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
执行后,您将收到以下结果。在内部循环中,您有一个 break 命令,参数为 2。这表示,如果满足条件,则您应该退出外部循环,并最终也退出内部循环。
Upon execution, you will receive the following result. In the inner loop, you have a break command with the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately from the inner loop as well.
1 0
1 5
The continue statement
continue 语句类似于 break 命令,只不过它导致退出循环的当前迭代,而不是整个循环。
The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop.
出现错误但您希望尝试执行循环的下一个迭代时,此语句很有用。
This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop.
Syntax
continue
与 break 语句一样,可以向 continue 命令提供一个整数参数,以便从嵌套循环中跳过命令。
Like with the break statement, an integer argument can be given to the continue command to skip commands from nested loops.
continue n
这里 n 指定了继续执行的 nth 循环。
Here n specifies the nth enclosing loop to continue from.
Example
以下循环使用 continue 语句,它从 continue 语句返回并开始处理下一条语句 −
The following loop makes use of the continue statement which returns from the continue statement and starts processing the next statement −
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Unix - Shell Substitution
What is Substitution?
当 Shell 遇到包含一个或多个特殊字符的表达式时,它会执行替换。
The shell performs substitution when it encounters an expression that contains one or more special characters.
Example
此处,变量的打印值被替换为其值。同时, "\n" 被替换为换行符 −
Here, the printing value of the variable is substituted by its value. Same time, "\n" is substituted by a new line −
#!/bin/sh
a=10
echo -e "Value of a is $a \n"
您会收到以下结果。在此处 -e 选项允许解释反斜杠转义符。
You will receive the following result. Here the -e option enables the interpretation of backslash escapes.
Value of a is 10
以下是没有 -e 选项的结果 −
Following is the result without -e option −
Value of a is 10\n
本教程中用到了可用于 echo 命令的下列转义序列——
Here are following escape sequences which can be used in echo command −
Sr.No. |
Escape & Description |
1 |
\\ backslash |
2 |
\a alert (BEL) |
3 |
\b backspace |
4 |
*\c * suppress trailing newline |
5 |
*\f * form feed |
6 |
\n new line |
7 |
\r carriage return |
8 |
*\t * horizontal tab |
9 |
*\v * vertical tab |
您可以使用 -E 选项禁用对反斜杠转义符的解释(默认)。
You can use the -E option to disable the interpretation of the backslash escapes (default).
您可以使用 -n 选项禁用插入换行符。
You can use the -n option to disable the insertion of a new line.
Command Substitution
命令替换是一种机制,通过该机制,Shell 执行一组给定的命令,然后用这些命令的输出替换命令。
Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.
Syntax
当给出命令时,执行命令替换 −
The command substitution is performed when a command is given as −
`command`
在执行命令替换时,请确保使用反引号,而不是单引号字符。
When performing the command substitution make sure that you use the backquote, not the single quote character.
Example
命令替换通常用于将命令的输出分配给变量。以下每个示例都展示了命令替换 −
Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrates the command substitution −
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Date is Thu Jul 2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul 2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15
Variable Substitution
变量替换使 Shell 程序员能够根据变量的状态来操作变量的值。
Variable substitution enables the shell programmer to manipulate the value of a variable based on its state.
以下是所有可能替换操作的表格 −
Here is the following table for all the possible substitutions −
Sr.No. |
Form & Description |
1 |
${var} Substitute the value of var. |
2 |
${var:-word} If var is null or unset, word is substituted for var. The value of var does not change. |
3 |
${var:=word} If var is null or unset, var is set to the value of word. |
4 |
${var:?message} If var is null or unset, message is printed to standard error. This checks that variables are set correctly. |
5 |
${var:+word} If var is set, word is substituted for var. The value of var does not change. |
Example
以下示例显示了上述替换的各种状态 −
Following is the example to show various states of the above substitution −
#!/bin/sh
echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"
echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix
Unix - Shell Quoting Mechanisms
在本章中,我们将详细讨论 Shell 引用机制。我们将从讨论元字符开始。
In this chapter, we will discuss in detail about the Shell quoting mechanisms. We will start by discussing the metacharacters.
The Metacharacters
Unix Shell 提供了各种元字符,在任何 Shell 脚本中使用它们时都具有特殊含义,并且会导致某个单词终止,除非加引号。
Unix Shell provides various metacharacters which have special meaning while using them in any Shell Script and causes termination of a word unless quoted.
例如, ? 与目录中列出的单个字符匹配,而 * 与多个字符匹配。以下是大多数 shell 特殊字符(也称为元字符)的列表 −
For example, ? matches with a single character while listing files in a directory and an * matches more than one character. Here is a list of most of the shell special characters (also called metacharacters) −
* ? [ ] ' " \ $ ; & ( ) | ^ < > new-line space tab
通过在字符前加上 \ 可以引用一个字符(即,使它代表自身)。
A character may be quoted (i.e., made to stand for itself) by preceding it with a \.
Example
以下示例显示了如何打印 * 或 ? −
Following example shows how to print a * or a ? −
#!/bin/sh
echo Hello; Word
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Hello
./test.sh: line 2: Word: command not found
shell returned 127
我们现在尝试使用一个带引号的字符 −
Let us now try using a quoted character −
#!/bin/sh
echo Hello\; Word
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Hello; Word
$ 符号是元字符之一,因此必须加上引号以避免 shell 对其进行特殊处理 −
The $ sign is one of the metacharacters, so it must be quoted to avoid special handling by the shell −
#!/bin/sh
echo "I have \$1200"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
I have $1200
下表列出了四种引用形式 −
The following table lists the four forms of quoting −
Sr.No. |
Quoting & Description |
1 |
Single quote All special characters between these quotes lose their special meaning. |
2 |
Double quote Most special characters between these quotes lose their special meaning with these exceptions − $`\$\'\"\\ |
3 |
Backslash Any character immediately following the backslash loses its special meaning. |
4 |
Back quote Anything in between back quotes would be treated as a command and would be executed. |
The Single Quotes
考虑一个包含许多特殊 shell 字符的 echo 命令−
Consider an echo command that contains many special shell characters −
echo <-$1500.**>; (update?) [y|n]
在每个特殊字符前放置反斜杠既繁琐又增加了阅读的难度−
Putting a backslash in front of each special character is tedious and makes the line difficult to read −
echo \<-\$1500.\*\*\>\; \(update\?\) \[y\|n\]
有一种简单的方法可以引用一大组字符。在字符串的开头和结尾处放置单引号(')−
There is an easy way to quote a large group of characters. Put a single quote (') at the beginning and at the end of the string −
echo '<-$1500.**>; (update?) [y|n]'
单引号中的字符就像在每个字符前加上反斜杠一样被引用。使用这种方法,echo 命令可以正常显示。
Characters within single quotes are quoted just as if a backslash is in front of each character. With this, the echo command displays in a proper way.
如果字符串中出现单引号需要输出,你不应该将整个字符串放在单引号中,而应在该字符前加上反斜杠(\),如下所示−
If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\) as follows −
echo 'It\'s Shell Programming
The Double Quotes
尝试执行以下 shell 脚本。此 shell 脚本使用了单引号−
Try to execute the following shell script. This shell script makes use of single quote −
VAR=ZARA
echo '$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]'
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]
这不是预期要显示的内容。很明显,单引号可以防止变量替换。如果你希望替换变量值并让引号正常工作,那么你需要将命令放入双引号中,如下所示−
This is not what had to be displayed. It is obvious that single quotes prevent variable substitution. If you want to substitute variable values and to make inverted commas work as expected, then you would need to put your commands in double quotes as follows −
VAR=ZARA
echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
ZARA owes <-$1500.**>; [ as of (07/02) ]
双引号消除了除以下字符之外所有字符的特殊含义−
Double quotes take away the special meaning of all characters except the following −
-
$ for parameter substitution
-
Backquotes for command substitution
-
\$ to enable literal dollar signs
-
\` to enable literal backquotes
-
\" to enable embedded double quotes
-
\\ to enable embedded backslashes
-
All other \ characters are literal (not special)
单引号中的字符就像在每个字符前加上反斜杠一样被引用。这有助于 echo 命令正确显示。
Characters within single quotes are quoted just as if a backslash is in front of each character. This helps the echo command display properly.
如果字符串中出现单引号需要输出,你不应该将整个字符串放在单引号中,而应在该字符前加上反斜杠(\),如下所示−
If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash (\) as follows −
echo 'It\'s Shell Programming'
The Backquotes
将任何 Shell 命令放入 backquotes 中会执行该命令。
Putting any Shell command in between backquotes executes the command.
Syntax
以下是将任何 Shell command 放入反引号中的简单语法−
Here is the simple syntax to put any Shell command in between backquotes −
var=`command`
Example
在以下示例中, date 命令被执行,而产生的结果存储在 DATA 变量中。
The date command is executed in the following example and the produced result is stored in DATA variable.
DATE=`date`
echo "Current Date: $DATE"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
Current Date: Thu Jul 2 05:28:45 MST 2009
Unix - Shell Input/Output Redirections
在本章中,我们将详细讨论 Shell 输入/输出重定向。大多数 Unix 系统命令从你的终端获取输入并将产生的输出发回你的终端。一个命令通常从标准输入读取其输入,而默认情况下你的终端就是标准输入。类似地,一个命令通常将它的输出写入到标准输出,而默认情况下你的终端也是标准输出。
In this chapter, we will discuss in detail about the Shell input/output redirections. Most Unix system commands take input from your terminal and send the resulting output back to your terminal. A command normally reads its input from the standard input, which happens to be your terminal by default. Similarly, a command normally writes its output to standard output, which is again your terminal by default.
Output Redirection
本来打算用作标准输出的命令输出可以轻松地改发到文件。这种功能称为输出重定向。
The output from a command normally intended for standard output can be easily diverted to a file instead. This capability is known as output redirection.
如果符号 > file 附加到任何通常将它的输出写入到标准输出的命令,那么该命令的输出将被写入到 file 而不是你的终端。
If the notation > file is appended to any command that normally writes its output to standard output, the output of that command will be written to file instead of your terminal.
查看以下 who 命令,它将命令的完整输出重定向到 users 文件。
Check the following who command which redirects the complete output of the command in the users file.
$ who > users
请注意,没有输出出现在终端上。这是因为输出已被从默认的标准输出设备(终端)重定向到了指定的文件中。你可以查看 users 文件以获得完整内容 −
Notice that no output appears at the terminal. This is because the output has been redirected from the default standard output device (the terminal) into the specified file. You can check the users file for the complete content −
$ cat users
oko tty01 Sep 12 07:30
ai tty15 Sep 12 13:32
ruth tty21 Sep 12 10:10
pat tty24 Sep 12 13:07
steve tty25 Sep 12 13:03
$
如果一个命令的输出被重定向到一个文件且该文件已经包含了一些数据,那么那些数据将被丢失。考虑以下示例 −
If a command has its output redirected to a file and the file already contains some data, that data will be lost. Consider the following example −
$ echo line 1 > users
$ cat users
line 1
$
您可以使用 >> 运算符将输出附加到现有文件中,如下所示:
You can use >> operator to append the output in an existing file as follows −
$ echo line 2 >> users
$ cat users
line 1
line 2
$
Input Redirection
与将命令的输出重定向到文件一样,也可以将命令的输入重定向到文件。与 greater-than character > 用于输出重定向一样, less-than character < 用于重定向命令的输入。
Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. As the greater-than character > is used for output redirection, the less-than character < is used to redirect the input of a command.
通常从标准输入获取输入的命令可以以这种方式将它们的输入重定向到一个文件中。例如,要计算上面由用户生成的文本文件中的行数,您可以执行如下命令:
The commands that normally take their input from the standard input can have their input redirected from a file in this manner. For example, to count the number of lines in the file users generated above, you can execute the command as follows −
$ wc -l users
2 users
$
执行后,您将收到以下输出。您可以通过将 wc 命令的标准输入从文件用户重定向来计算文件中行的数量:
Upon execution, you will receive the following output. You can count the number of lines in the file by redirecting the standard input of the wc command from the file users −
$ wc -l < users
2
$
请注意,wc 命令产生的两种形式的输出存在差异。在第一种情况下,文件 users 的名称用引号与行数列在一起;在第二种情况下,则没有。
Note that there is a difference in the output produced by the two forms of the wc command. In the first case, the name of the file users is listed with the line count; in the second case, it is not.
在第一种情况下,wc 知道它正在从文件 users 读取输入。在第二种情况下,它只知道它正在从标准输入读取输入,因此它不显示文件名称。
In the first case, wc knows that it is reading its input from the file users. In the second case, it only knows that it is reading its input from standard input so it does not display file name.
Here Document
here document 用于将输入重定向到交互式 shell 脚本或程序。
A here document is used to redirect input into an interactive shell script or program.
我们可以在 shell 脚本中运行一个交互式程序,而无需用户操作,方法是为交互式程序或交互式 shell 脚本提供所需的输入。
We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script.
here 文档的一般形式是:
The general form for a here document is −
command << delimiter
document
delimiter
这里 shell 将 << 运算符解释为一个指令,指在它找到包含指定分界符的行之前,读取输入。然后将包含分界符的行之前的全部输入行送入命令的标准输入。
Here the shell interprets the << operator as an instruction to read input until it finds a line containing the specified delimiter. All the input lines up to the line containing the delimiter are then fed into the standard input of the command.
分界符告诉 shell, here 文档已完成。如果没有分界符,shell 将继续永远读取输入。分界符必须是不包含空格或选项卡的单个单词。
The delimiter tells the shell that the here document has completed. Without it, the shell continues to read the input forever. The delimiter must be a single word that does not contain spaces or tabs.
以下是对命令 wc -l 的输入,用于计算总行数:
Following is the input to the command wc -l to count the total number of lines −
$wc -l << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF
3
$
您可以使用 here document 来使用您的脚本打印多行,如下所示:
You can use the here document to print multiple lines using your script as follows −
#!/bin/sh
cat << EOF
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
EOF
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.
以下脚本运行了文本编辑器 vi 的一个会话,并将输入保存在文件 test.txt 中。
The following script runs a session with the vi text editor and saves the input in the file test.txt.
#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands
如果您使用 vim 作为 vi 运行此脚本,那么您可能会看到如下的输出:
If you run this script with vim acting as vi, then you will likely see output like the following −
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
运行脚本后,您应该看到以下内容被添加到文件 test.txt 中:
After running the script, you should see the following added to the file test.txt −
$ cat test.txt
This file was created automatically from
a shell script
$
Discard the output
有时您需要执行命令,但是您不想在屏幕上显示输出。在这种情况下,您可以通过将输出重定向到文件 /dev/null 来丢弃输出:
Sometimes you will need to execute a command, but you don’t want the output displayed on the screen. In such cases, you can discard the output by redirecting it to the file /dev/null −
$ command > /dev/null
这里 command 是您要执行的命令的名称。文件 /dev/null 是一个特殊文件,自动丢弃其所有输入。
Here command is the name of the command you want to execute. The file /dev/null is a special file that automatically discards all its input.
要丢弃命令的输出及其错误输出,请使用标准重定向将 STDERR 重定向到 STDOUT :
To discard both output of a command and its error output, use standard redirection to redirect STDERR to STDOUT −
$ command > /dev/null 2>&1
此处 2 表示 STDERR ,而 1 表示 STDOUT 。您可以将消息重定向到 STDERR,方法是将 STDOUT 重定向到 STDERR,如下所示 −
Here 2 represents STDERR and 1 represents STDOUT. You can display a message on to STDERR by redirecting STDOUT into STDERR as follows −
$ echo message 1>&2
Redirection Commands
以下是可用于重定向的命令的完整列表 −
Following is a complete list of commands which you can use for redirection −
Sr.No. |
Command & Description |
1 |
pgm > file Output of pgm is redirected to file |
2 |
pgm < file Program pgm reads its input from file |
3 |
pgm >> file Output of pgm is appended to file |
4 |
n > file Output from stream with descriptor n redirected to file |
5 |
n >> file Output from stream with descriptor n appended to file |
6 |
n >& m Merges output from stream n with stream m |
7 |
n <& m Merges input from stream n with stream m |
8 |
<< tag Standard input comes from here through next tag at the start of line |
9 |
* |
请注意,文件描述符 0 通常是标准输入 (STDIN), 1 是标准输出 (STDOUT),而 2 是标准错误输出 (STDERR)。
Note that the file descriptor 0 is normally standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).
Unix - Shell Functions
在本章中,我们将详细讨论 Shell 函数。使用函数可以将脚本的整体功能分解为更小的逻辑子部分,然后根据需要调用它们来执行各自的任务。
In this chapter, we will discuss in detail about the shell functions. Functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their individual tasks when needed.
使用函数执行重复任务是创建 code reuse 的绝佳方式。这是现代面向对象编程原则的重要组成部分。
Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an important part of modern object-oriented programming principles.
Shell 函数类似于其他编程语言中的子例程、过程和函数。
Shell functions are similar to subroutines, procedures, and functions in other programming languages.
Creating Functions
要声明函数,只需使用以下语法:
To declare a function, simply use the following syntax −
function_name () {
list of commands
}
函数的名称是 function_name ,您将在脚本中的其他地方使用它来调用此函数。函数名称后面必须紧跟括号,然后是一对大括号中包含的命令列表。
The name of your function is function_name, and that’s what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.
Pass Parameters to a Function
您可以在调用函数时定义一个接受参数的函数。这些参数将由 $1 、 $2 等表示。
You can define a function that will accept parameters while calling the function. These parameters would be represented by $1, $2 and so on.
以下是一个示例,其中我们传递两个参数 Zara 和 Ali,然后在函数中捕获并打印这些参数。
Following is an example where we pass two parameters Zara and Ali and then we capture and print these parameters in the function.
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Returning Values from Functions
如果您从函数内部执行 exit 命令,其效果不仅会终止函数的执行,还会终止调用该函数的 shell 程序。
If you execute an exit command from inside a function, its effect is not only to terminate execution of the function but also of the shell program that called the function.
如果您只想终止函数的执行,则有方法退出已定义的函数。
If you instead want to just terminate execution of the function, then there is way to come out of a defined function.
根据具体情况,您可以使用 return 命令从函数返回任何值,其语法如下:
Based on the situation you can return any value from your function using the return command whose syntax is as follows −
return code
此处 code 可以是您选择的内容,但显然您应该选择在整个脚本上下文中具有意义或有用的内容。
Here code can be anything you choose here, but obviously you should choose something that is meaningful or useful in the context of your script as a whole.
Example
以下函数返回一个值 10:
Following function returns a value 10 −
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Return value is 10
Nested Functions
函数一个更有趣的功能是它们可以调用它们自己以及其他函数。调用自身的函数称为 recursive function 。
One of the more interesting features of functions is that they can call themselves and also other functions. A function that calls itself is known as a recursive function.
以下示例演示两个函数的嵌套 –
Following example demonstrates nesting of two functions −
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
执行后,您会收到以下结果 −
Upon execution, you will receive the following result −
This is the first function speaking...
This is now the second function speaking...
Function Call from Prompt
可以在 .profile 内放置常用函数的定义。每当你登录时,这些定义都会可用,你可以在命令提示符中使用这些定义。
You can put definitions for commonly used functions inside your .profile. These definitions will be available whenever you log in and you can use them at the command prompt.
或者,你可以将定义分组放在一个文件中,称为 test.sh ,然后通过键入以下内容在当前 shell 中执行文件 –
Alternatively, you can group the definitions in a file, say test.sh, and then execute the file in the current shell by typing −
$. test.sh
这会产生一个效果,就是由 test.sh 定义的函数被读入并定义到当前 shell,如下所示 –
This has the effect of causing functions defined inside test.sh to be read and defined to the current shell as follows −
$ number_one
This is the first function speaking...
This is now the second function speaking...
$
若要从 shell 中删除函数定义,请使用 unset 命令和 .f 选项。此命令还用于删除对 shell 的变量定义。
To remove the definition of a function from the shell, use the unset command with the .f option. This command is also used to remove the definition of a variable to the shell.
$ unset -f function_name
Unix - Shell Manpage Help
所有 Unix 命令都带有一些可选项和必选项。忘记这些命令的完整语法很常见。
All the Unix commands come with a number of optional and mandatory options. It is very common to forget the complete syntax of these commands.
因为没有人可能记住每一个 Unix 命令和它的所有选项,因此,我们拥有在线帮助来缓解这一点,并且这种在线帮助 منذ أن كان Unix 处于开发阶段起就可用了。
Because no one can possibly remember every Unix command and all its options, we have online help available to mitigate this right from when Unix was at its development stage.
Unix 的下载版本 Help files 称为 man pages 。如果有一个命令名称,你不确定如何使用它,那么手册页可以帮你解决每一步。
Unix’s version of Help files are called man pages. If there is a command name and you are not sure how to use it, then Man Pages help you out with every step.
Syntax
这是一个简单的命令,它可以帮助你获取任何 Unix 命令的详细信息,同时与系统一起使用:
Here is the simple command that helps you get the detail of any Unix command while working with the system −
$man command
Example
假设有一条命令要求您获得帮助;假设您想要了解 pwd ,那么您只需使用以下命令:
Suppose there is a command that requires you to get help; assume that you want to know about pwd then you simply need to use the following command −
$man pwd
上述命令可帮助您获得 pwd 命令的完整信息。在您的命令提示符处自己尝试一下以获取更多详细信息。
The above command helps you with the complete information about the pwd command. Try it yourself at your command prompt to get more detail.
您可以使用以下命令来获取 man 命令本身的完整信息:
You can get complete detail on man command itself using the following command −
$man man
Man Page Sections
手册页通常分为几节,一般根据手册页作者的偏好而有所不同。下表列出了一些常见部分:
Man pages are generally divided into sections, which generally vary by the man page author’s preference. Following table lists some common sections −
Sr.No. |
Section & Description |
1 |
NAME Name of the command |
2 |
SYNOPSIS General usage parameters of the command |
3 |
DESCRIPTION Describes what the command does |
4 |
OPTIONS Describes all the arguments or options to the command |
5 |
SEE ALSO Lists other commands that are directly related to the command in the man page or closely resemble its functionality |
6 |
BUGS Explains any known issues or bugs that exist with the command or its output |
7 |
EXAMPLES Common usage examples that give the reader an idea of how the command can be used |
8 |
AUTHORS The author of the man page/command |
总而言之,手册页是一项至关重要的资源,当您需要有关 Unix 系统中的命令或文件的信息时,它是一种首要的研究途径。
To sum it up, man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system.
Useful Shell Commands
以下链接为您提供了最重要的和最常用的 Unix Shell 命令列表。
The following link gives you a list of the most important and very frequently used Unix Shell commands.
如果您不知道如何使用任何命令,请使用手册页来了解有关该命令的完整详细信息。
If you do not know how to use any command, then use man page to get complete detail about the command.
以下是 Unix Shell - Useful Commands 的列表:
Here is the list of Unix Shell - Useful Commands
Unix - Regular Expressions with SED
在本篇教程中,我们将详细讨论 Unix 中的 SED 正则表达式。
In this chapter, we will discuss in detail about regular expressions with SED in Unix.
正则表达式是一个可以用来描述多个字符序列的字符串。包括 ed 、 sed 、 awk 、 grep 等许多不同的 Unix 命令都使用了正则表达式,在一定程度上甚至包括 vi 。
A regular expression is a string that can be used to describe several sequences of characters. Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.
此处 SED 代表 *s*tream *ed*itor。此流定向编辑器完全用于执行脚本。因此,你输入其中的所有内容都将经过处理并传递到 STDOUT,并且它不会改变输入文件。
Here SED stands for *s*tream *ed*itor. This stream-oriented editor was created exclusively for executing scripts. Thus, all the input you feed into it passes through and goes to STDOUT and it does not change the input file.
Invoking sed
在正式开始之前,我们先确保有一份 /etc/passwd 文本文件的本地副本,以便进行练习 sed 。
Before we start, let us ensure we have a local copy of /etc/passwd text file to work with sed.
如前文所述,通过管道向 sed 发送数据就可以调用它,如下所示——
As mentioned previously, sed can be invoked by sending data through a pipe to it as follows −
$ cat /etc/passwd | sed
Usage: sed [OPTION]... {script-other-script} [input-file]...
-n, --quiet, --silent
suppress automatic printing of pattern space
-e script, --expression = script
...............................
cat 命令通过管道将 /etc/passwd 的内容转储到 sed ,再转储到 sed 的模式空间。模式空间是 sed 用于执行操作的内部工作缓冲区。
The cat command dumps the contents of /etc/passwd to sed through the pipe into sed’s pattern space. The pattern space is the internal work buffer that sed uses for its operations.
The sed General Syntax
以下是 sed 的通用语法——
Following is the general syntax for sed −
/pattern/action
此处, pattern 是正则表达式,而 action 是下表中给出的一个命令。如果 pattern 被忽略,则对每一行执行 action ,如我们在上面看到的那样。
Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above.
把模式包围起来的斜杠 (/)是必需的,因为它们用作分隔符。
The slash character (/) that surrounds the pattern are required because they are used as delimiters.
Sr.No. |
Range & Description |
1 |
p Prints the line |
2 |
d Deletes the line |
3 |
s/pattern1/pattern2/ Substitutes the first occurrence of pattern1 with pattern2 |
Deleting All Lines with sed
现在我们将了解如何使用 sed 删除所有行。再次调用 sed;但是,现在 sed 应该使用 editing command delete line ,该字符用字母 d - 表示
We will now understand how to delete all lines with sed. Invoke sed again; but the sed is now supposed to use the editing command delete line, denoted by the single letter d −
$ cat /etc/passwd | sed 'd'
$
不需要通过管道向 sed 发送文件即可调用 sed,可以指示 sed 从文件读取数据,如下面的示例所示。
Instead of invoking sed by sending a file to it through a pipe, the sed can be instructed to read the data from a file, as in the following example.
以下命令与前一个示例中的命令完全相同,不需要 cat 命令:
The following command does exactly the same as in the previous example, without the cat command −
$ sed -e 'd' /etc/passwd
$
The sed Addresses
sed 还支持地址。地址要么是文件中的特定位置,要么是应该应用特定编辑命令的范围。当 sed 遇到没有地址时,它会在文件中的每一行执行操作。
The sed also supports addresses. Addresses are either particular locations in a file or a range where a particular editing command should be applied. When the sed encounters no addresses, it performs its operations on every line in the file.
以下命令向您已在使用的 sed 命令添加了基本地址:
The following command adds a basic address to the sed command you’ve been using −
$ cat /etc/passwd | sed '1d' |more
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
$
请注意,该 delete edit 命令前添加了数字 1。这指示 sed 对文件的第 1 行执行编辑命令。在此示例中,sed 将删除 /etc/password 的第一行并打印文件的其余部分。
Notice that the number 1 is added before the delete edit command. This instructs the sed to perform the editing command on the first line of the file. In this example, the sed will delete the first line of /etc/password and print the rest of the file.
The sed Address Ranges
现在我们将了解如何使用 the sed address ranges 。那么,如果您想从文件中移除多行,该怎么办?您可以用 sed 指定一个地址范围,如下所示:
We will now understand how to work with the sed address ranges. So what if you want to remove more than one line from a file? You can specify an address range with sed as follows −
$ cat /etc/passwd | sed '1, 5d' |more
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
$
上述命令将应用于从 1 到 5 开始的所有行。这会删除前五行。
The above command will be applied on all the lines starting from 1 through 5. This deletes the first five lines.
尝试以下地址范围:
Try out the following address ranges −
Sr.No. |
Range & Description |
1 |
'4,10d' Lines starting from the 4th till the 10th are deleted |
2 |
'10,4d' Only 10th line is deleted, because the sed does not work in reverse direction |
3 |
'4,+5d' This matches line 4 in the file, deletes that line, continues to delete the next five lines, and then ceases its deletion and prints the rest |
4 |
'2,5!d' This deletes everything except starting from 2nd till 5th line |
5 |
'1~3d' This deletes the first line, steps over the next three lines, and then deletes the fourth line. Sed continues to apply this pattern until the end of the file. |
6 |
'2~2d' This tells sed to delete the second line, step over the next line, delete the next line, and repeat until the end of the file is reached |
7 |
'4,10p' Lines starting from 4th till 10th are printed |
8 |
'4,d' This generates the syntax error |
9 |
',10d' This would also generate syntax error |
Note − 在使用 p 操作时,您应该使用 -n 选项来避免重复打印行。查看以下两个命令之间的差异 −
Note − While using the p action, you should use the -n option to avoid repetition of line printing. Check the difference in between the following two commands −
$ cat /etc/passwd | sed -n '1,3p'
Check the above command without -n as follows −
$ cat /etc/passwd | sed '1,3p'
The Substitution Command
由 s 表示的替换命令将用您指定的任何其他字符串替换您指定的任何字符串。
The substitution command, denoted by s, will substitute any string that you specify with any other string that you specify.
为了用一个字符串替换另一个字符串,sed 需要有关第一个字符串结束位置和替换字符串开始位置的信息。为此,我们使用正斜杠 ( / ) 字符将这两个字符串作为书挡。
To substitute one string with another, the sed needs to have the information on where the first string ends and the substitution string begins. For this, we proceed with bookending the two strings with the forward slash (/) character.
以下命令用字符串 amrood 替换一行中字符串 root 的首次出现。
The following command substitutes the first occurrence on a line of the string root with the string amrood.
$ cat /etc/passwd | sed 's/root/amrood/'
amrood:x:0:0:root user:/root:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
..........................
需要注意的是,sed 仅替换一行中的首次出现。如果字符串 root 在一行中出现多次,则仅替换第一个匹配项。
It is very important to note that sed substitutes only the first occurrence on a line. If the string root occurs more than once on a line only the first match will be replaced.
为了让 sed 执行全局替换,请按以下方式将字母 g 添加到命令的末尾 −
For the sed to perform a global substitution, add the letter g to the end of the command as follows −
$ cat /etc/passwd | sed 's/root/amrood/g'
amrood:x:0:0:amrood user:/amrood:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
...........................
Substitution Flags
除了 g 标志外,还可以传递许多其他有用的标志,并且您一次可以指定多个标志。
There are a number of other useful flags that can be passed in addition to the g flag, and you can specify more than one at a time.
Sr.No. |
Flag & Description |
1 |
g Replaces all matches, not just the first match |
2 |
NUMBER Replaces only NUMBERth match |
3 |
p If substitution was made, then prints the pattern space |
4 |
w FILENAME If substitution was made, then writes result to FILENAME |
5 |
I or i Matches in a case-insensitive manner |
6 |
M or m In addition to the normal behavior of the special regular expression characters ^ and $, this flag causes ^ to match the empty string after a newline and $ to match the empty string before a newline |
Using an Alternative String Separator
假设您必须对包含正斜杠字符的字符串执行替换。在这种情况下,您可以通过在 s 后提供指定字符来指定不同的分隔符。
Suppose you have to do a substitution on a string that includes the forward slash character. In this case, you can specify a different separator by providing the designated character after the s.
$ cat /etc/passwd | sed 's:/root:/amrood:g'
amrood:x:0:0:amrood user:/amrood:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
在上面的示例中,我们使用了 : 作为 delimiter 而不是斜杠 /,因为我们试图搜索 /root 而不是简单的 root。
In the above example, we have used : as the delimiter instead of slash / because we were trying to search /root instead of the simple root.
Replacing with Empty Space
使用空替换字符串从 /etc/passwd 文件中完全删除 root 字符串 −
Use an empty substitution string to delete the root string from the /etc/passwd file entirely −
$ cat /etc/passwd | sed 's/root//g'
:x:0:0::/:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
Address Substitution
如果您只想在第 10 行上用字符串 quiet 替换字符串 sh ,则可以按如下方式指定:
If you want to substitute the string sh with the string quiet only on line 10, you can specify it as follows −
$ cat /etc/passwd | sed '10s/sh/quiet/g'
root:x:0:0:root user:/root:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/quiet
类似地,要进行地址范围替换,您可以执行以下操作:
Similarly, to do an address range substitution, you could do something like the following −
$ cat /etc/passwd | sed '1,5s/sh/quiet/g'
root:x:0:0:root user:/root:/bin/quiet
daemon:x:1:1:daemon:/usr/sbin:/bin/quiet
bin:x:2:2:bin:/bin:/bin/quiet
sys:x:3:3:sys:/dev:/bin/quiet
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
正如您从输出中看到的,前五行的字符串 sh 已更改为 quiet ,但其余行保持不变。
As you can see from the output, the first five lines had the string sh changed to quiet, but the rest of the lines were left untouched.
The Matching Command
您将使用 p 选项和 -n 选项来打印所有匹配行,如下所示:
You would use the p option along with the -n option to print all the matching lines as follows −
$ cat testing | sed -n '/root/p'
root:x:0:0:root user:/root:/bin/sh
[root@ip-72-167-112-17 amrood]# vi testing
root:x:0:0:root user:/root:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
Using Regular Expression
在匹配模式时,可以使用正则表达式,它提供更大的灵活性。
While matching patterns, you can use the regular expression which provides more flexibility.
检查以下示例,它匹配以 daemon 开头的所有行,然后删除它们 −
Check the following example which matches all the lines starting with daemon and then deletes them −
$ cat testing | sed '/^daemon/d'
root:x:0:0:root user:/root:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
以下是删除所有以 sh 结尾的行的示例 −
Following is the example which deletes all the lines ending with sh −
$ cat testing | sed '/sh$/d'
sync:x:4:65534:sync:/bin:/bin/sync
下表列出了四个在正则表达式中非常有用的特殊字符。
The following table lists four special characters that are very useful in regular expressions.
Sr.No. |
Character & Description |
1 |
^ Matches the beginning of lines |
2 |
$ Matches the end of lines |
3 |
. Matches any single character |
4 |
* Matches zero or more occurrences of the previous character |
5 |
[chars] Matches any one of the characters given in chars, where chars is a sequence of characters. You can use the - character to indicate a range of characters. |
Matching Characters
再看一些表达式,以演示 metacharacters 的用法。例如,以下模式 −
Look at a few more expressions to demonstrate the use of metacharacters. For example, the following pattern −
Sr.No. |
Expression & Description |
1 |
/a.c/ Matches lines that contain strings such as a+c, a-c, abc, match, and a3c |
2 |
/a*c/ Matches the same strings along with strings such as ace, yacc, and arctic |
3 |
/[tT]he/ Matches the string The and the |
4 |
/^$/ Matches blank lines |
5 |
/^.$/* Matches an entire line whatever it is |
6 |
/ */ Matches one or more spaces |
7 |
/^$/ Matches blank lines |
下表显示了一些常用字符集 −
Following table shows some frequently used sets of characters −
Sr.No. |
Set & Description |
1 |
[a-z] Matches a single lowercase letter |
2 |
[A-Z] Matches a single uppercase letter |
3 |
[a-zA-Z] Matches a single letter |
4 |
[0-9] Matches a single number |
5 |
[a-zA-Z0-9] Matches a single letter or number |
Character Class Keywords
某些特殊关键字通常可用于 regexps ,尤其是使用 regexps 的 GNU 实用程序。这些对于 sed 正则表达式非常有用,因为它们简化了操作并增强了可读性。
Some special keywords are commonly available to regexps, especially GNU utilities that employ regexps. These are very useful for sed regular expressions as they simplify things and enhance readability.
For example, the characters a through z and the characters A through Z, constitute one such class of characters that has the keyword [id=":alpha:"]
使用字母字符类关键字,此命令只打印 /etc/syslog.conf 文件中以字母开头的行 −
Using the alphabet character class keyword, this command prints only those lines in the /etc/syslog.conf file that start with a letter of the alphabet −
$ cat /etc/syslog.conf | sed -n '/^[[:alpha:]]/p'
authpriv.* /var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log
下表是 GNU sed 中可用字符类关键字的完整列表。
The following table is a complete list of the available character class keywords in GNU sed.
Sr.No. |
Character Class & Description |
1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
[id=":print:"] Printable characters (non-control characters) |
9 |
|
10 |
|
11 |
|
12 |
Aampersand Referencing
sed metacharacter & 表示匹配的模式的内容。例如,假设你有一个名为 phone.txt 的文件,其中包含许多电话号码,如下所示 −
The sed metacharacter & represents the contents of the pattern that was matched. For instance, say you have a file called phone.txt full of phone numbers, such as the following −
5555551212
5555551213
5555551214
6665551215
6665551216
7775551217
你想将 area code (前三个数字)括在括号中以方便阅读。为此,你可以使用替换字符“&” −
You want to make the area code (the first three digits) surrounded by parentheses for easier reading. To do this, you can use the ampersand replacement character −
$ sed -e 's/^[[:digit:]][[:digit:]][[:digit:]]/(&)/g' phone.txt
(555)5551212
(555)5551213
(555)5551214
(666)5551215
(666)5551216
(777)5551217
在模式部分,你匹配前 3 个数字,然后使用 & 来用 parentheses 包围替换这 3 个数字。
Here in the pattern part you are matching the first 3 digits and then using & you are replacing those 3 digits with the surrounding parentheses.
Using Multiple sed Commands
你可以使用以下方法在单个 sed 命令中使用多个 sed 命令 −
You can use multiple sed commands in a single sed command as follows −
$ sed -e 'command1' -e 'command2' ... -e 'commandN' files
此处 command1 到 commandN 为前面讨论过的类型 sed 命令。这些命令应用于给定文件中列表中的每一行。
Here command1 through commandN are sed commands of the type discussed previously. These commands are applied to each of the lines in the list of files given by files.
使用相同机制,我们可以如下编写上面的电话号码示例 −
Using the same mechanism, we can write the above phone number example as follows −
$ sed -e 's/^[[:digit:]]\{3\}/(&)/g' \
-e 's/)[[:digit:]]\{3\}/&-/g' phone.txt
(555)555-1212
(555)555-1213
(555)555-1214
(666)555-1215
(666)555-1216
(777)555-1217
Back References
ampersand metacharacter 很有用,但更重要的是能够定义正则表达式中的特定区域。这些特殊区域可以用作替换字符串中的参考。通过定义正则表达式的特定部分,你可以使用特殊参考字符引用这些部分。
The ampersand metacharacter is useful, but even more useful is the ability to define specific regions in regular expressions. These special regions can be used as reference in your replacement strings. By defining specific parts of a regular expression, you can then refer back to those parts with a special reference character.
要执行 back references ,你必须先定义一个区域,然后引用该区域。要定义一个区域,你可以在每个感兴趣的区域周围插入 backslashed parentheses 。你用反斜杠包围的第一个区域由 \1 引用,第二个区域由 \2 引用,依此类推。
To do back references, you have to first define a region and then refer back to that region. To define a region, you insert backslashed parentheses around each region of interest. The first region that you surround with backslashes is then referenced by \1, the second region by \2, and so on.
假设 phone.txt 具有以下文本 −
Assuming phone.txt has the following text −
(555)555-1212
(555)555-1213
(555)555-1214
(666)555-1215
(666)555-1216
(777)555-1217
尝试以下命令 −
Try the following command −
$ cat phone.txt | sed 's/\(.*)\)\(.*-\)\(.*$\)/Area \
code: \1 Second: \2 Third: \3/'
Area code: (555) Second: 555- Third: 1212
Area code: (555) Second: 555- Third: 1213
Area code: (555) Second: 555- Third: 1214
Area code: (666) Second: 555- Third: 1215
Area code: (666) Second: 555- Third: 1216
Area code: (777) Second: 555- Third: 1217
Note − 在上述示例中,括号内的每个正则表达式都将由 \1 、 \2 等进行反向引用。我们在此处使用 \ 来换行。在运行命令之前,应该将其删除。
Note − In the above example, each regular expression inside the parenthesis would be back referenced by \1, \2 and so on. We have used \ to give line break here. This should be removed before running the command.
Unix - File System Basics
文件系统是分区或磁盘上的文件的逻辑集合。分区是信息的容器,可以跨越整个硬盘,如果需要的话。
A file system is a logical collection of files on a partition or disk. A partition is a container for information and can span an entire hard drive if desired.
您的硬盘可以有各种分区,这些分区通常只包含一个文件系统,例如一个文件系统容纳 /file system 或另一个包含 /home file system 。
Your hard drive can have various partitions which usually contain only one file system, such as one file system housing the /file system or another containing the /home file system.
每个分区一个文件系统可以对不同的文件系统进行逻辑维护和管理。
One file system per partition allows for the logical maintenance and management of differing file systems.
在 Unix 中,所有内容都被认为是一个文件,包括物理设备,例如 DVD-ROM、USB 设备和软盘驱动器。
Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs, USB devices, and floppy drives.
Directory Structure
Unix 使用分层文件系统结构,非常像一棵倒置的树,其中根 (/) 位于文件系统的底部,所有其他目录都从那里展开。
Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the base of the file system and all other directories spreading from there.
Unix 文件系统是一组文件和目录,具有以下属性:
A Unix filesystem is a collection of files and directories that has the following properties −
-
It has a root directory (/) that contains other files and directories.
-
Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode.
-
By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command.
-
It is self-contained. There are no dependencies between one filesystem and another.
目录有特定的用途,通常保存相同类型的信息,以便轻松地查找文件。下面是在 Unix 主要版本中存在的目录:
The directories have specific purposes and generally hold the same types of information for easily locating files. Following are the directories that exist on the major versions of Unix −
Sr.No. |
Directory & Description |
1 |
/ This is the root directory which should contain only the directories needed at the top level of the file structure |
2 |
/bin This is where the executable files are located. These files are available to all users |
3 |
/dev These are device drivers |
4 |
/etc Supervisor directory commands, configuration files, disk configuration files, valid user lists, groups, ethernet, hosts, where to send critical messages |
5 |
/lib Contains shared library files and sometimes other kernel-related files |
6 |
/boot Contains files for booting the system |
7 |
/home Contains the home directory for users and other accounts |
8 |
/mnt Used to mount other temporary file systems, such as cdrom and floppy for the CD-ROM drive and floppy diskette drive, respectively |
9 |
/proc Contains all processes marked as a file by process number or other information that is dynamic to the system |
10 |
/tmp Holds temporary files used between system boots |
11 |
/usr Used for miscellaneous purposes, and can be used by many users. Includes administrative commands, shared files, library files, and others |
12 |
/var Typically contains variable-length files such as log and print files and any other type of file that may contain a variable amount of data |
13 |
/sbin Contains binary (executable) files, usually for system administration. For example, fdisk and ifconfig utlities |
14 |
/kernel Contains kernel files |
Navigating the File System
现在您已经了解了文件系统的基础知识,即可开始导航到所需文件。以下命令用于导航系统:
Now that you understand the basics of the file system, you can begin navigating to the files you need. The following commands are used to navigate the system −
Sr.No. |
Command & Description |
1 |
cat filename Displays a filename |
2 |
cd dirname Moves you to the identified directory |
3 |
cp file1 file2 Copies one file/directory to the specified location |
4 |
file filename Identifies the file type (binary, text, etc) |
5 |
find filename dir Finds a file/directory |
6 |
head filename Shows the beginning of a file |
7 |
less filename Browses through a file from the end or the beginning |
8 |
ls dirname Shows the contents of the directory specified |
9 |
mkdir dirname Creates the specified directory |
10 |
more filename Browses through a file from the beginning to the end |
11 |
mv file1 file2 Moves the location of, or renames a file/directory |
12 |
pwd Shows the current directory the user is in |
13 |
rm filename Removes a file |
14 |
rmdir dirname Removes a directory |
15 |
tail filename Shows the end of a file |
16 |
touch filename Creates a blank file or modifies an existing file or its attributes |
17 |
whereis filename Shows the location of a file |
18 |
which filename Shows the location of a file if it is in your PATH |
您可以使用 Manpage Help 查看此处提到的每个命令的完整语法。
You can use Manpage Help to check complete syntax for each command mentioned here.
The df Command
管理分区空间的第一种方法是使用 df (disk free) 命令。命令 df -k (disk free) 显示 disk space usage in kilobytes ,如下所示:
The first way to manage your partition space is with the df (disk free) command. The command df -k (disk free) displays the disk space usage in kilobytes, as shown below −
$df -k
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/vzfs 10485760 7836644 2649116 75% /
/devices 0 0 0 0% /devices
$
某些目录,如 /devices 在 kbytes 中显示 0,使用的和可用的列以及容量的 0%。这些是特殊(或虚拟)文件系统,尽管它们驻留在 / 下的磁盘上,但本身不占用磁盘空间。
Some of the directories, such as /devices, shows 0 in the kbytes, used, and avail columns as well as 0% for capacity. These are special (or virtual) file systems, and although they reside on the disk under /, by themselves they do not consume disk space.
df -k 输出在所有 Unix 系统上通常都是相同的。以下是它通常包括的内容:
The df -k output is generally the same on all Unix systems. Here’s what it usually includes −
Sr.No. |
Column & Description |
1 |
Filesystem The physical file system name |
2 |
kbytes Total kilobytes of space available on the storage medium |
3 |
used Total kilobytes of space used (by files) |
4 |
avail Total kilobytes available for use |
5 |
capacity Percentage of total space used by files |
6 |
Mounted on What the file system is mounted on |
您可以使用 -h (human readable) option 以更容易理解的符号显示输出格式。
You can use the -h (human readable) option to display the output in a format that shows the size in easier-to-understand notation.
The du Command
du (disk usage) command 使您能够指定目录以显示特定目录的磁盘空间使用情况。
The du (disk usage) command enables you to specify directories to show disk space usage on a particular directory.
如果您想确定某个目录占用了多少空间,此命令很有用。以下命令显示每个目录消耗的块数。根据您的系统,单个块可能占用 512 字节或 1 千字节。
This command is helpful if you want to determine how much space a particular directory is taking. The following command displays number of blocks consumed by each directory. A single block may take either 512 Bytes or 1 Kilo Byte depending on your system.
$du /etc
10 /etc/cron.d
126 /etc/default
6 /etc/dfs
...
$
-h 选项能让输出更易于理解 −
The -h option makes the output easier to comprehend −
$du -h /etc
5k /etc/cron.d
63k /etc/default
3k /etc/dfs
...
$
Mounting the File System
文件系统必须被挂载才能被系统使用。要查看系统当前挂载(可用于使用)的内容,请使用以下命令 −
A file system must be mounted in order to be usable by the system. To see what is currently mounted (available for use) on your system, use the following command −
$ mount
/dev/vzfs on / type reiserfs (rw,usrquota,grpquota)
proc on /proc type proc (rw,nodiratime)
devpts on /dev/pts type devpts (rw)
$
按照 Unix 公约, /mnt 目录是临时挂载(例如 CDROM 驱动器、远程网络驱动器和软盘驱动器)的位置。如果需要挂载文件系统,则可按以下语法使用 mount 命令 −
The /mnt directory, by the Unix convention, is where temporary mounts (such as CDROM drives, remote network drives, and floppy drives) are located. If you need to mount a file system, you can use the mount command with the following syntax −
mount -t file_system_type device_to_mount directory_to_mount_to
例如,如果要将 CD-ROM 挂载到 /mnt/cdrom 目录,则可输入 −
For example, if you want to mount a CD-ROM to the directory /mnt/cdrom, you can type −
$ mount -t iso9660 /dev/cdrom /mnt/cdrom
这假设您的 CD-ROM 设备名为 /dev/cdrom ,并且您希望将其挂载到 /mnt/cdrom 。有关更具体的信息,请参阅 mount 手册页,或在命令行中输入 mount -h 以获取帮助信息。
This assumes that your CD-ROM device is called /dev/cdrom and that you want to mount it to /mnt/cdrom. Refer to the mount man page for more specific information or type mount -h at the command line for help information.
挂载后,您可以使用 cd 命令通过刚刚创建的挂载点来导航新可用的文件系统。
After mounting, you can use the cd command to navigate the newly available file system through the mount point you just made.
Unmounting the File System
要卸载(移除)系统中的文件系统,请使用 umount 命令识别挂载点或设备。
To unmount (remove) the file system from your system, use the umount command by identifying the mount point or device.
例如, to unmount cdrom ,使用以下命令 −
For example, to unmount cdrom, use the following command −
$ umount /dev/cdrom
mount command 使您能够访问自己的文件系统,但在大多数现代 Unix 系统上, automount function 使此进程对于用户来说不可见,无需介入。
The mount command enables you to access your file systems, but on most modern Unix systems, the automount function makes this process invisible to the user and requires no intervention.
User and Group Quotas
用户配额和组配额提供了限制单个用户或特定组内所有用户所用空间量的机制,可限制为管理员定义的值。
The user and group quotas provide the mechanisms by which the amount of space used by a single user or all users within a specific group can be limited to a value defined by the administrator.
配额围绕两个限制运行,在空间量或磁盘块数开始超过管理员定义的限制时,允许用户采取一些措施 −
Quotas operate around two limits that allow the user to take some action if the amount of space or number of disk blocks start to exceed the administrator defined limits −
-
Soft Limit − If the user exceeds the limit defined, there is a grace period that allows the user to free up some space.
-
Hard Limit − When the hard limit is reached, regardless of the grace period, no further files or blocks can be allocated.
有多个用于管理配额的命令 −
There are a number of commands to administer quotas −
Sr.No. |
Command & Description |
1 |
quota Displays disk usage and limits for a user of group |
2 |
edquota This is a quota editor. Users or Groups quota can be edited using this command |
3 |
quotacheck Scans a filesystem for disk usage, creates, checks and repairs quota files |
4 |
setquota This is a command line quota editor |
5 |
quotaon This announces to the system that disk quotas should be enabled on one or more filesystems |
6 |
quotaoff This announces to the system that disk quotas should be disabled for one or more filesystems |
7 |
repquota This prints a summary of the disc usage and quotas for the specified file systems |
您可以使用 Manpage Help 查看此处提到的每个命令的完整语法。
You can use Manpage Help to check complete syntax for each command mentioned here.
Unix - User Administration
在本章中,我们将详细讨论 Unix 中的用户管理。
In this chapter, we will discuss in detail about user administration in Unix.
Unix 系统上有三种类型的帐户 -
There are three types of accounts on a Unix system −
Root account
这也是 superuser ,将拥有对系统的完整和不受限制的控制。超级用户可以在没有任何限制的情况下运行任何命令。此用户应被假定为系统管理员。
This is also called superuser and would have complete and unfettered control of the system. A superuser can run any commands without any restriction. This user should be assumed as a system administrator.
System accounts
系统帐户是为特定组件的运行而必需的,例如邮件帐户和 sshd 帐户。这些帐户通常在系统上需要一些特定功能,对它们的任何修改都可能对系统产生不利影响。
System accounts are those needed for the operation of system-specific components for example mail accounts and the sshd accounts. These accounts are usually needed for some specific function on your system, and any modifications to them could adversely affect the system.
User accounts
用户账户为用户及其用户组提供对系统的交互式访问权限。一般用户通常被分配到这些账户,并且通常对关键系统文件和目录的访问权限有限。
User accounts provide interactive access to the system for users and groups of users. General users are typically assigned to these accounts and usually have limited access to critical system files and directories.
Unix 支持组账户的概念,其逻辑上分组了多个账户。每个账户都将成为另一个组账户的一部分。Unix 组在处理文件权限和进程管理中扮演着重要角色。
Unix supports a concept of Group Account which logically groups a number of accounts. Every account would be a part of another group account. A Unix group plays important role in handling file permissions and process management.
Managing Users and Groups
有四个主要的用户管理文件 −
There are four main user administration files −
-
/etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system.
-
/etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file.
-
/etc/group − This file contains the group information for each account.
-
/etc/gshadow − This file contains secure group account information.
使用 cat 命令检查以上所有文件。
Check all the above files using the cat command.
下表列出了大多数 Unix 系统上可用于创建和管理账户及组的命令 −
The following table lists out commands that are available on majority of Unix systems to create and manage accounts and groups −
Sr.No. |
Command & Description |
1 |
useradd Adds accounts to the system |
2 |
usermod Modifies account attributes |
3 |
userdel Deletes accounts from the system |
4 |
groupadd Adds groups to the system |
5 |
groupmod Modifies group attributes |
6 |
groupdel Removes groups from the system |
您可以使用 Manpage Help 查看此处提到的每个命令的完整语法。
You can use Manpage Help to check complete syntax for each command mentioned here.
Create a Group
我们现在了解如何创建组。为此,我们需要在创建任何账户之前创建组,否则,我们可以使用系统中的现有组。我们已将所有组列在 /etc/groups 文件中。
We will now understand how to create a group. For this, we need to create groups before creating any account otherwise, we can make use of the existing groups in our system. We have all the groups listed in /etc/groups file.
所有默认组都是特定于系统账户的组,不建议将其用于普通账户。因此,以下是如何创建新组账户的语法 −
All the default groups are system account specific groups and it is not recommended to use them for ordinary accounts. So, following is the syntax to create a new group account −
groupadd [-g gid [-o]] [-r] [-f] groupname
下表列出了参数 −
The following table lists out the parameters −
Sr.No. |
Option & Description |
1 |
-g GID The numerical value of the group’s ID |
2 |
-o This option permits to add group with non-unique GID |
3 |
-r This flag instructs groupadd to add a system account |
4 |
*-f * This option causes to just exit with success status, if the specified group already exists. With -g, if the specified GID already exists, other (unique) GID is chosen |
5 |
groupname Actual group name to be created |
如果您未指定任何参数,则系统会使用默认值。
If you do not specify any parameter, then the system makes use of the default values.
以下示例使用大多数管理员都极易接受的默认值创建了 developers 组。
Following example creates a developers group with default values, which is very much acceptable for most of the administrators.
$ groupadd developers
Modify a Group
要修改组,请使用 groupmod 语法 −
To modify a group, use the groupmod syntax −
$ groupmod -n new_modified_group_name old_group_name
要将 developers_2 组名更改为 developer,请键入 −
To change the developers_2 group name to developer, type −
$ groupmod -n developer developer_2
下面是将 financial GID 更改为 545 的方法 −
Here is how you will change the financial GID to 545 −
$ groupmod -g 545 developer
Delete a Group
我们现在将了解如何删除组。要删除现有组,您只需要 groupdel command 和 group name 。要删除 financial 组,命令为 −
We will now understand how to delete a group. To delete an existing group, all you need is the groupdel command and the group name. To delete the financial group, the command is −
$ groupdel developer
这仅删除组,而不删除与此组关联的文件。文件仍可由其所有者访问。
This removes only the group, not the files associated with that group. The files are still accessible by their owners.
Create an Account
让我们看看如何在 Unix 系统上创建新帐户。以下是创建用户帐户的语法 −
Let us see how to create a new account on your Unix system. Following is the syntax to create a user’s account −
useradd -d homedir -g groupname -m -s shell -u userid accountname
下表列出了参数 −
The following table lists out the parameters −
Sr.No. |
Option & Description |
1 |
-d homedir Specifies home directory for the account |
2 |
-g groupname Specifies a group account for this account |
3 |
-m Creates the home directory if it doesn’t exist |
4 |
-s shell Specifies the default shell for this account |
5 |
-u userid You can specify a user id for this account |
6 |
accountname Actual account name to be created |
如果您未指定任何参数,则系统会使用默认值。 useradd 命令会修改 /etc/passwd 、 /etc/shadow 和 /etc/group 文件,并创建主目录。
If you do not specify any parameter, then the system makes use of the default values. The useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files and creates a home directory.
以下示例创建了一个名为 mcmohd 的帐户,将其主目录设置为 /home/mcmohd ,并将组设置为 developers 。此用户已将 Korn Shell 分配给它。
Following is the example that creates an account mcmohd, setting its home directory to /home/mcmohd and the group as developers. This user would have Korn Shell assigned to it.
$ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd
在发出上述命令之前,请确保已使用 groupadd 命令创建了 developers 组。
Before issuing the above command, make sure you already have the developers group created using the groupadd command.
创建帐号后,你可以使用 passwd 命令设置其密码,如下所示:
Once an account is created you can set its password using the passwd command as follows −
$ passwd mcmohd20
Changing password for user mcmohd20.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
当你键入 passwd accountname 时,它会给你一个更改密码选项,前提是你是超级用户。否则,你只能使用同一命令更改你的密码,但不指定你的帐号名称。
When you type passwd accountname, it gives you an option to change the password, provided you are a superuser. Otherwise, you can change just your password using the same command but without specifying your account name.
Modify an Account
usermod 命令让你能够从命令行更改现有帐号。它使用与 useradd 命令相同的参数,加上 -l 参数,它允许你更改帐号名称。
The usermod command enables you to make changes to an existing account from the command line. It uses the same arguments as the useradd command, plus the -l argument, which allows you to change the account name.
例如,要把帐号名称 mcmohd 更改为 mcmohd20 ,并相应更改主目录,你需要发出以下命令:
For example, to change the account name mcmohd to mcmohd20 and to change home directory accordingly, you will need to issue the following command −
$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20
Delete an Account
userdel 命令可以用来删除现有用户。如果不谨慎使用,这是一个非常危险的命令。
The userdel command can be used to delete an existing user. This is a very dangerous command if not used with caution.
命令 .r 只有一个可用的参数或选项,用于移除此帐号的主目录和邮件文件。
There is only one argument or option available for the command .r, for removing the account’s home directory and mail file.
例如,要删除帐号 mcmohd20,请发出以下命令:
For example, to remove account mcmohd20, issue the following command −
$ userdel -r mcmohd20
如果你想保留主目录以备将来用,请省略 -r 选项。你可以在以后的需要时删除主目录。
If you want to keep the home directory for backup purposes, omit the -r option. You can remove the home directory as needed at a later time.
Unix - System Performance
在本章中,我们将详细讨论 Unix 系统的系统性能。
In this chapter, we will discuss in detail about the system performance in Unix.
我们将向你介绍几个可用来监控和管理 Unix 系统性能的免费工具。这些工具还提供了关于如何诊断和修复 Unix 环境中的性能问题的指南。
We will introduce you to a few free tools that are available to monitor and manage performance on Unix systems. These tools also provide guidelines on how to diagnose and fix performance problems in the Unix environment.
Unix 具有以下需要监控和调整的主要资源类型:
Unix has following major resource types that need to be monitored and tuned −
-
CPU
-
Memory
-
Disk space
-
Communications lines
-
I/O Time
-
Network Time
-
Applications programs
Performance Components
下表列出了占用系统时间的五个主要组件:
The following table lists out five major components which take up the system time −
Sr.No. |
Component & Description |
1 |
User State CPU The actual amount of time the CPU spends running the users’ program in the user state. It includes the time spent executing library calls, but does not include the time spent in the kernel on its behalf |
2 |
System State CPU * This is the amount of time the CPU spends in the system state on behalf of this program. All *I/O routines require kernel services. The programmer can affect this value by blocking I/O transfers |
3 |
*I/O Time and Network Time * This is the amount of time spent moving data and servicing I/O requests |
4 |
*Virtual Memory Performance * This includes context switching and swapping |
5 |
Application Program Time spent running other programs - when the system is not servicing this application because another application currently has the CPU |
Performance Tools
Unix 提供了以下重要工具来测量和微调 Unix 系统性能:
Unix provides following important tools to measure and fine tune Unix system performance −
Sr.No. |
Command & Description |
1 |
nice/renice Runs a program with modified scheduling priority |
2 |
netstat Prints network connections, routing tables, interface statistics, masquerade connections, and multicast memberships |
3 |
time Helps time a simple command or give resource usage |
4 |
uptime This is System Load Average |
5 |
ps Reports a snapshot of the current processes |
6 |
vmstat Reports virtual memory statistics |
7 |
gprof Displays call graph profile data |
8 |
prof Facilitates Process Profiling |
9 |
top Displays system tasks |
您可以使用 Manpage Help 查看此处提到的每个命令的完整语法。
You can use Manpage Help to check complete syntax for each command mentioned here.
Unix - System Logging
在本章中,我们将详细讨论 Unix 中的系统日志记录。
In this chapter, we will discuss in detail about system logging in Unix.
Unix 系统拥有非常灵活而强大的日志记录系统,它让你能够记录你所能想象的几乎所有内容,然后操作日志来检索所需的信息。
Unix systems have a very flexible and powerful logging system, which enables you to record almost anything you can imagine and then manipulate the logs to retrieve the information you require.
许多版本的 Unix 提供了一个称为 syslog 的通用日志记录工具。需要记录信息的各个程序会将信息发送到 syslog。
Many versions of Unix provide a general-purpose logging facility called syslog. Individual programs that need to have information logged, send the information to syslog.
Unix syslog 是一种可由主机配置的统一系统日志记录工具。该系统使用一个集中式系统日志记录进程,它运行程序 /etc/syslogd 或 /etc/syslog 。
Unix syslog is a host-configurable, uniform system logging facility. The system uses a centralized system logging process that runs the program /etc/syslogd or /etc/syslog.
系统记录器的运行非常直接。程序会将日志条目发送至 syslogd,syslogd 会查阅配置文件 /etc/syslogd.conf 或 /etc/syslog ,并在找到匹配时将日志消息写入所需的日志文件。
The operation of the system logger is quite straightforward. Programs send their log entries to syslogd, which consults the configuration file /etc/syslogd.conf or /etc/syslog and, when a match is found, writes the log message to the desired log file.
有四个基本的 syslog 术语你需要掌握 -
There are four basic syslog terms that you should understand −
Sr.No. |
Term & Description |
1 |
Facility The identifier used to describe the application or process that submitted the log message. For example, mail, kernel, and ftp. |
2 |
Priority An indicator of the importance of the message. Levels are defined within syslog as guidelines, from debugging information to critical events. |
3 |
Selector A combination of one or more facilities and levels. When an incoming event matches a selector, an action is performed. |
4 |
Action What happens to an incoming message that matches a selector — Actions can write the message to a log file, echo the message to a console or other device, write the message to a logged in user, or send the message along to another syslog server. |
Syslog Facilities
我们现在将了解 syslog 工具。以下是选择器的可用工具。并非所有工具都在 Unix 的所有版本中都存在。
We will now understand about the syslog facilities. Here are the available facilities for the selector. Not all facilities are present on all versions of Unix.
Facility |
Description |
1 |
auth Activity related to requesting name and password (getty, su, login) |
2 |
authpriv Same as auth but logged to a file that can only be read by selected users |
3 |
console Used to capture messages that are generally directed to the system console |
4 |
cron Messages from the cron system scheduler |
5 |
daemon System daemon catch-all |
6 |
ftp Messages relating to the ftp daemon |
7 |
kern Kernel messages |
8 |
local0.local7 Local facilities defined per site |
9 |
lpr Messages from the line printing system |
10 |
mail Messages relating to the mail system |
11 |
mark Pseudo-event used to generate timestamps in log files |
12 |
news Messages relating to network news protocol (nntp) |
13 |
ntp Messages relating to network time protocol |
14 |
user Regular user processes |
15 |
uucp UUCP subsystem |
Syslog Priorities
syslog 优先级汇总在以下表格中
The syslog priorities are summarized in the following table −
Sr.No. |
Priority & Description |
1 |
emerg Emergency condition, such as an imminent system crash, usually broadcast to all users |
2 |
alert Condition that should be corrected immediately, such as a corrupted system database |
3 |
crit Critical condition, such as a hardware error |
4 |
err Ordinary error |
5 |
Warning Warning |
6 |
notice Condition that is not an error, but possibly should be handled in a special way |
7 |
info Informational message |
8 |
debug Messages that are used when debugging programs |
9 |
none Pseudo level used to specify not to log messages |
设施和级别的组合使您能够明辨要记录的内容以及这些信息存放的位置。
The combination of facilities and levels enables you to be discerning about what is logged and where that information goes.
随着每个程序尽职尽责地将自己的消息发送到系统日志,日志记录器将根据选择器中定义的级别,决定跟踪哪些内容,以及丢弃哪些内容。
As each program sends its messages dutifully to the system logger, the logger makes decisions on what to keep track of and what to discard based on the levels defined in the selector.
当你指定一个级别,系统将跟踪该级别及更高级别下的所有信息。
When you specify a level, the system will keep track of everything at that level and higher.
The /etc/syslog.conf file
/etc/syslog.conf 文件控制日志消息记录的位置。一个典型的 syslog.conf 文件可能如下所示 −
The /etc/syslog.conf file controls where messages are logged. A typical syslog.conf file might look like this −
*.err;kern.debug;auth.notice /dev/console
daemon,auth.notice /var/log/messages
lpr.info /var/log/lpr.log
mail.* /var/log/mail.log
ftp.* /var/log/ftp.log
auth.* @prep.ai.mit.edu
auth.* root,amrood
netinfo.err /var/log/netinfo.log
install.* /var/log/install.log
*.emerg *
*.alert |program_name
mark.* /dev/console
该文件的每一个行包含两个部分 −
Each line of the file contains two parts −
-
A message selector that specifies which kind of messages to log. For example, all error messages or all debugging messages from the kernel.
-
An action field that says what should be done with the message. For example, put it in a file or send the message to a user’s terminal.
以下是上述配置的值得关注的要点 −
Following are the notable points for the above configuration −
-
Message selectors have two parts: a facility and a priority. For example, kern.debug selects all debug messages (the priority) generated by the kernel (the facility).
-
Message selector kern.debug selects all priorities that are greater than debug.
-
An asterisk in place of either the facility or the priority indicates "all". For example, .debug means all debug messages, while kern. means all messages generated by the kernel.
-
You can also use commas to specify multiple facilities. Two or more selectors can be grouped together by using a semicolon.
Logging Actions
操作字段指定五个操作中的一个 −
The action field specifies one of five actions −
-
Log message to a file or a device. For example, /var/log/lpr.log or /dev/console.
-
Send a message to a user. You can specify multiple usernames by separating them with commas; for example, root, amrood.
-
Send a message to all users. In this case, the action field consists of an asterisk; for example, *.
-
Pipe the message to a program. In this case, the program is specified after the Unix pipe symbol (|).
-
Send the message to the syslog on another host. In this case, the action field consists of a hostname, preceded by an at sign; for example, @tutorialspoint.com.
The logger Command
Unix 提供了 logger 命令,这是一个非常有用的命令,用于处理系统日志记录。 logger 命令将日志记录消息发送到 syslogd 守护程序,并因此触发系统日志记录。
Unix provides the logger command, which is an extremely useful command to deal with system logging. The logger command sends logging messages to the syslogd daemon, and consequently provokes system logging.
这意味着我们可以随时从命令行中查看 syslogd 守护程序及其配置。logger 命令提供了一种从命令行向系统日志文件添加单行条目的方法。
This means we can check from the command line at any time the syslogd daemon and its configuration. The logger command provides a method for adding one-line entries to the system log file from the command line.
命令的格式为 −
The format of the command is −
logger [-i] [-f file] [-p priority] [-t tag] [message]...
以下是参数的说明:
Here is the detail of the parameters −
Sr.No. |
Option & Description |
1 |
-f filename Uses the contents of file filename as the message to log. |
2 |
-i Logs the process ID of the logger process with each line. |
3 |
-p priority Enters the message with the specified priority (specified selector entry); the message priority can be specified numerically, or as a facility.priority pair. The default priority is user.notice. |
4 |
-t tag Marks each line added to the log with the specified tag. |
5 |
message The string arguments whose contents are concatenated together in the specified order, separated by the space. |
你可以使用 Manpage Help 检查此命令的完整语法。
You can use Manpage Help to check complete syntax for this command.
Log Rotation
日志文件有很快速增长和占用大量磁盘空间的趋势。为了启用日志轮换,大多数发行版会使用诸如 newsyslog 或 logrotate 的工具。
Log files have the propensity to grow very fast and consume large amounts of disk space. To enable log rotations, most distributions use tools such as newsyslog or logrotate.
这些工具应该使用 cron daemon 在频繁的时间间隔内被调用。查看 newsyslog 或 logrotate 的手册页以获得更多详细信息。
These tools should be called on a frequent time interval using the cron daemon. Check the man pages for newsyslog or logrotate for more details.
Important Log Locations
所有系统应用程序都在 /var/log 及其子目录中创建它们的日志文件。以下是一些重要的应用程序及其对应的日志目录 −
All the system applications create their log files in /var/log and its sub-directories. Here are few important applications and their corresponding log directories −
Application |
Directory |
httpd |
/var/log/httpd |
samba |
/var/log/samba |
cron |
/var/log/ |
/var/log/ |
|
mysql |
/var/log/ |
Unix - Signals and Traps
在本章中,我们将详细讨论 Unix 中的信号和陷阱。
In this chapter, we will discuss in detail about Signals and Traps in Unix.
信号是发送到程序中的软件中断,用于指明重要事件已发生。事件可以从用户请求到非法内存访问错误。一些信号(例如中断信号)表明用户已要求程序执行不在通常控制流中的操作。
Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control.
下表列出了你可能遇到的和希望在程序中使用的常见信号 -
The following table lists out common signals you might encounter and want to use in your programs −
Signal Name |
Signal Number |
Description |
SIGHUP |
1 |
Hang up detected on controlling terminal or death of controlling process |
SIGINT |
2 |
Issued if the user sends an interrupt signal (Ctrl + C) |
SIGQUIT |
3 |
Issued if the user sends a quit signal (Ctrl + D) |
SIGFPE |
8 |
Issued if an illegal mathematical operation is attempted |
SIGKILL |
9 |
If a process gets this signal it must quit immediately and will not perform any clean-up operations |
SIGALRM |
14 |
Alarm clock signal (used for timers) |
SIGTERM |
15 |
Software termination signal (sent by kill by default) |
List of Signals
有一种简单的方法可以列出系统支持的所有信号。只需发出 kill -l 命令,它将显示所有受支持的信号 -
There is an easy way to list down all the signals supported by your system. Just issue the kill -l command and it would display all the supported signals −
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
信号的实际列表因 Solaris、HP-UX 和 Linux 而异。
The actual list of signals varies between Solaris, HP-UX, and Linux.
Default Actions
每个信号都有与其关联的默认操作。信号的默认操作是脚本或程序在接收到信号时执行的操作。
Every signal has a default action associated with it. The default action for a signal is the action that a script or program performs when it receives a signal.
一些可能的默认操作 -
Some of the possible default actions are −
-
Terminate the process.
-
Ignore the signal.
-
Dump core. This creates a file called core containing the memory image of the process when it received the signal.
-
Stop the process.
-
Continue a stopped process.
Sending Signals
有几种将信号传递给程序或脚本的方法。最常见的方法之一是让用户在脚本执行时键入 CONTROL-C 或 INTERRUPT key 。
There are several methods of delivering signals to a program or script. One of the most common is for a user to type CONTROL-C or the INTERRUPT key while a script is executing.
当您按下 Ctrl+C 键时,一条 SIGINT 被发送到脚本中,并且根据定义的默认操作脚本终止。
When you press the Ctrl+C key, a SIGINT is sent to the script and as per defined default action script terminates.
发出信号的另一种常用方法是使用 kill command ,其语法如下 −
The other common method for delivering signals is to use the kill command, the syntax of which is as follows −
$ kill -signal pid
其中 signal 是要发送的信号的号码或名称, pid 是要向其发送信号的进程 ID。例如 −
Here signal is either the number or name of the signal to deliver and pid is the process ID that the signal should be sent to. For Example −
$ kill -1 1001
上述命令将 HUP 或挂起信号发送到正在使用 process ID 1001 运行的程序。要向同一进程发送终止信号,请使用以下命令 −
The above command sends the HUP or hang-up signal to the program that is running with process ID 1001. To send a kill signal to the same process, use the following command −
$ kill -9 1001
这将杀死正在使用 process ID 1001 运行的进程。
This kills the process running with process ID 1001.
Trapping Signals
当你在终端执行 shell 程序时按下 Ctrl+C 或 Break 键时,通常该程序会立即终止,并且你的命令提示符会返回。这可能并不总是需要的。例如,你最终可能会留下一些未清理的临时文件。
When you press the Ctrl+C or Break key at your terminal during execution of a shell program, normally that program is immediately terminated, and your command prompt returns. This may not always be desirable. For instance, you may end up leaving a bunch of temporary files that won’t get cleaned up.
捕获这些信号非常容易,并且陷阱命令具有以下语法:
Trapping these signals is quite easy, and the trap command has the following syntax −
$ trap commands signals
在这里,command 可以是任何有效的 Unix 命令,甚至可以是用户定义的函数,而 signal 可能是你想要捕获的任何数量信号的列表。
Here command can be any valid Unix command, or even a user-defined function, and signal can be a list of any number of signals you want to trap.
在 shell 脚本中,trap 有两种常见用法:
There are two common uses for trap in shell scripts −
-
Clean up temporary files
-
Ignore signals
Cleaning Up Temporary Files
作为 trap 命令的示例,以下显示了当有人尝试从终端中止程序时,如何删除一些文件并随后退出:
As an example of the trap command, the following shows how you can remove some files and then exit if someone tries to abort the program from the terminal −
$ trap "rm -f $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 2
从执行此陷阱的 shell 程序开始,如果程序收到信号号 2,将会自动删除这两个文件 work1 和 dataout 。
From the point in the shell program that this trap is executed, the two files work1 and dataout will be automatically removed if signal number 2 is received by the program.
因此,如果用户在此陷阱执行后中断程序的执行,你可以确保会清理这两个文件。紧随 rm 之后的 exit 命令是必需的,因为没有它,执行将在接收到信号时停止的位置继续进行。
Hence, if the user interrupts the execution of the program after this trap is executed, you can be assured that these two files will be cleaned up. The exit command that follows the rm is necessary because without it, the execution would continue in the program at the point that it left off when the signal was received.
信号号 1 为 hangup 生成。有人故意挂断电话线或电话线意外断开。
Signal number 1 is generated for hangup. Either someone intentionally hangs up the line or the line gets accidentally disconnected.
你可以通过向信号列表中添加信号号 1 来修改前面的 trap,以便在此情况下也删除两个指定的文件:
You can modify the preceding trap to also remove the two specified files in this case by adding signal number 1 to the list of signals −
$ trap "rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 1 2
现在,如果电话挂断或按下 Ctrl+C 键,这些文件将被删除。
Now these files will be removed if the line gets hung up or if the Ctrl+C key gets pressed.
如果指定的陷阱命令包含不止一个命令,则必须用引号引起来。还要注意,shell 在执行 trap 命令和接收到其中一个列出的信号时扫描命令行。
The commands specified to trap must be enclosed in quotes, if they contain more than one command. Also note that the shell scans the command line at the time that the trap command gets executed and also when one of the listed signals is received.
因此,在前面的示例中, WORKDIR 和 $$ 的值将在执行 trap 命令时进行替换。如果你希望在接收到信号 1 或 2 时执行此替换,可以将命令放在单引号中:
Thus, in the preceding example, the value of WORKDIR and $$ will be substituted at the time that the trap command is executed. If you wanted this substitution to occur at the time that either signal 1 or 2 was received, you can put the commands inside single quotes −
$ trap 'rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit' 1 2
Ignoring Signals
如果为 trap 列出的命令为空,则在接收到指定信号时将忽略该信号。例如,命令:
If the command listed for trap is null, the specified signal will be ignored when received. For example, the command −
$ trap '' 2
这指定了要忽略中断信号。你在执行不想被中断的操作时可能希望忽略某些信号。你可以指定要忽略的多个信号,如下所示:
This specifies that the interrupt signal is to be ignored. You might want to ignore certain signals when performing an operation that you don’t want to be interrupted. You can specify multiple signals to be ignored as follows −
$ trap '' 1 2 3 15
请注意,必须指定第一个参数才能忽略信号,并且不等于写以下内容,后者有其自己的单独含义:
Note that the first argument must be specified for a signal to be ignored and is not equivalent to writing the following, which has a separate meaning of its own −
$ trap 2
如果你忽略信号,所有子 shell 也将忽略该信号。但是,如果你指定在接收到信号时执行某个操作,则所有子 shell 在接收到该信号时仍将执行默认操作。
If you ignore a signal, all subshells also ignore that signal. However, if you specify an action to be taken on the receipt of a signal, all subshells will still take the default action on receipt of that signal.
Resetting Traps
在你更改了在接收到信号时执行的默认操作之后,如果你只省略第一个参数,你可以使用 trap 再次将其更改回来;因此:
After you’ve changed the default action to be taken on receipt of a signal, you can change it back again with the trap if you simply omit the first argument; so −
$ trap 1 2
这将接收到信号 1 或 2 时要执行的动作重置为默认值。
This resets the action to be taken on the receipt of signals 1 or 2 back to the default.