In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
The purpose of this article is to share with you about the nature and usage of Shell. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
1 、 shell
Key points: command line, standard input and standard output, redirection, piping, background running program, kill: terminating background job, file name generation / pathname expansion, built-in command
Shell is the user's system interface, which provides an interface for users to interact with the kernel. It receives the command entered by the user and sends it to the kernel for execution. Shell is actually a command interpreter that interprets commands entered by the user and sends them to the kernel.
1.1 Command Line
When you type the command enter at the command prompt, shell executes the appropriate program. For example, type ls and enter, and shell starts executing a tool called ls. You can also have shell execute other types of programs in the same way, such as shell scripts, applications, or programs written by yourself. The line that contains commands and parameters is called the command line. A command is a character typed on the command line, as well as the program invoked by the corresponding action.
1.1.1 Syntax
The command line syntax describes the order and spacing of the elements on the line. When the user types the command to enter, shell scans the command line for syntax checking. The basic syntax format on the command line is as follows:
Command [arg1]... [argn] RETURN
One or more spaces are used on the command line to separate each element. Where command is the name of the command, arg1 to argn are the parameters of the command, and enter is the key to terminate the command. Square brackets in the syntax format indicate that the enclosed parameters are optional. Not all commands require parameters, some commands have no parameters, some commands require a variable number of parameters, and some commands require a specific number of parameters. An option is a special type of parameter, usually preceded by one or two hyphens ("-" or "-").
1. Command name
Some useful Linux command lines consist only of command names without any arguments. For example, ls without any parameters will display a list of files in the working directory. Most commands take one or more parameters. When using commands with parameters, if there are no parameters, or incorrect parameters, or the wrong number of parameters, the system will return a short error message, which is called the command usage message (usage message).
two。 Parameters.
On the command line, each sequence of characters that does not contain space characters is called a token or word. A parameter is a token, such as a file name, text string, number, or other object processed by a command.
Here is a command line for cp:
The [root@QUFENGBIN ~] # cp temp tempcopy parameters are numbered, where the command itself is used as parameter 0, which is the beginning of the command line argument. In this example, the cp is parameter 0 and the temp is parameter 1 and the tempcopy is parameter 2. Cp requires at least two fields (you can also have more than one parameter, but not less than two), parameter 1 is the existing file name, and parameter 2 is the file to be created or rewritten by cp. Neither of these parameters is optional, but is required for the command to run.
PS:shell some special characters about parameters
The special character describes the PID (ProcessID) of $$Shell itself.
$! the PID of the background Process that the Shell last ran
$? The end code of the last run command (return value)
$- Flag list set using the Set command
$* list of all parameters. In the case of "$*" enclosed by "$", with "$1 $2". Outputs all parameters in the form of $n ".
$@ list of all parameters. In the case of "$@" surrounded by ", output all parameters in the form of" $1 "" $2 "…" $n ".
$# number of parameters added to Shell
The file name of the $0Shell itself
$1 parameter values added to the Shell. $1 is the first parameter, $2 is the second parameter.
[root@aminglinux_01 test] # cat test.shemale raceme bindingshecho "number:$#" echo "scname:$0" echo "first: $1" echo "second:$2" echo "argume:$@" [root@aminglinux_01 test] # sh test.sh aa bbnumber:2scname:test.shfirst: aasecond:bbargume:aa bb3. Option
The option (option) is a parameter that changes the effect of command execution. Commands can be executed in different ways by specifying multiple options. Options are related to a specific program and are interpreted by the program called on the command line, not by shell.
By convention, options are separate parameters that precede other parameters after the command, such as the file name. The options for most commands need to be preceded by a hyphen, but this requirement is tool-related, not shell-related. Options for GNU programs are usually preceded by two hyphens. For example,-- help generates usage messages.
4. Merge of option
When multiple options are needed, you can combine multiple single-character options into a single parameter, starting with a hyphen, without spaces before the options. However, two hyphens cannot be used before the merged option. The specific rules for merge options are related to the specific running program. The options for most commands are in no order.
5. Parameters of the option
Some tools have their own options with parameters. For example, the-o option of gcc (GUN's c compiler) must be followed by the executable file name generated by gcc, usually separated by a space from its parameters, as follows:
[root@QUFENGBIN] # gcc-o prog prog.c6. Parameters that begin with a hyphen
By convention, parameters of the tool, such as the file name, are allowed to start with a hyphen. In this way, when the name of a file is-l, the meaning of the command is not clear. If such a file is created, some commands agree to use-- (two consecutive hyphens) parameters to indicate the end of the option (and the beginning of the parameter). The following is an example:
[root@QUFENGBIN test] # touch-ltouch: invalid option-- 'l'Try' touch-- help' for more information. [root@QUFENGBIN test] # touch-l [root@QUFENGBIN test] # ls-ltotal 4Murray rwashi-1 root root 0 Apr 28 11:41-lafayashi-1 root root 14 Apr 26 16:26 test01 [root@QUFENGBIN test] # ls-- lMul [root@QUFENGBIN test] # ls-l-- 1 root root 0 Apr 28 11:41-l1.1.2 processing command line
When you type a command into the command line, Linux's tty device driver (part of the Linux operating system kernel) checks each character to determine whether to take action immediately. When a typed character does not require immediate action, the device driver stores the character in a buffer and waits for character input. When the enter key is pressed, the device driver will shell the command line transfer procedure.
1. Analyze the command line
When shell processes the command line, it treats the command line as a whole and divides it into several components. Next, shell will look for the name of the command. The first item after the prompt (that is, parameter 0) on the command line is usually the command name, so shell will take the string from the first character on the command line to the first white space character (TAB or space) as the command name. The command name (the first token) can be specified as a simple file name or path name. For example:
[root@QUFENGBIN test] # ls-l test01 [root@QUFENGBIN test] # / bin/ls-l test012. Absolute path name and relative path name
When you enter an absolute pathname or a relative pathname that is not a simple file name on the command line (that is, enter a pathname that contains at least one slash), shell looks for the corresponding file with execute permissions in the specified directory. For example, entering the command / bin/ls,shell will look for a file named ls that has execute permissions in the / bin directory. When a simple file name is entered, shell looks in a set of directories for a corresponding file that matches that file name and has execute permissions. Shell does not search in all directories, but only in the path set by the PATH variable.
1.1.3 execute command line 1. Process
If shell finds an executable file with the same name as a command on the command line, shell starts a new process (process refers to the execution of the Linux command) and passes the command name, parameters, and options on the command line to the program (executable). When the command is executed, the shell waits for the end of the process, and the shell is inactive, which is called hibernation. When the program finishes executing, its exit status is passed to shell, so that shell returns to its active state (awakened), displays a prompt, and waits for the next command to be entered.
Parameters not handled by 2.shell
Because shell does not process parameters on the command line, but simply passes them to the calling program, shell does not know whether the options and parameters are valid for the program. So error messages and usage messages about options and parameters come from the program itself. There are also commands that ignore invalid options.
1.2 Standard input and output
Standard output (standard output) refers to the place where a program outputs information, such as text. The program never "knows" where the information it sends to standard output goes. This information can be output to a printer, a normal file, or a screen. By default, shell outputs the results of the command to the screen. Shell can also redirect output to another file.
Standard input (standard input) is the source of program information. For standard output, the program never "knows" the source of the information. By default, the program's input comes from keyboard input.
For a running program, in addition to standard input and standard output, there is usually an error message output, called standard error output (standard error).
The command does not know where standard input comes from, nor does it know where standard output and standard error output go.
1.2.1 screen as a file
In addition to normal files, directory files, hard links, and soft links, Linux has another file type: device files (device file). Device files reside in the Linux file structure (usually in the directory / dev) and are used to represent peripherals such as terminal emulators, displays, printers, and hard drives.
In the content displayed by the who tool, the device name after the login name is the file name of the screen. If more than one window is open, each window has a corresponding device name. You can get their respective names by running the tty tool in these windows. You can think of this device file as a text file for reading and writing. Writing to the file displays what is written on the screen, and reading from the file reads what you type from the keyboard.
[root@QUFENGBIN test] # tty/dev/pts/0 [root@QUFENGBIN test] # whoroot tty1 2018-04-17 15:44root pts/0 2018-04-28 11:34 (111.113.5.18)
Chsh: change login shell
When setting up a user account, the system administrator will determine the shell that the user uses when logging in to the system for the first time or opening the terminal emulator window in the GUI environment (see / etc/passwd file).
Root:x:0:0:root:/root:/bin/bash.... .mysql: x:1000:1000::/home/mysql:/bin/falsewww:x:1001:1001::/home/www:/bin/falseapache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
However, after logging in to the system, the user can decide which shell to run. Type the name of the shell you want to use (such as bash,tcsh, or another shell), and then enter enter, and the prompt that appears is given by the newly set shell. Enter the exit command to return to the previous shell.
The login shell can be permanently modified using the tool chsh. First enter the command chsh, and then enter the password at the prompt and the absolute pathname of the shell you want to use (such as / bin/bash or / bin/tcsh, or the pathname of another shell).
1.2.2 Keyboard as standard input and screen as standard output
When logging in for the first time, shell sends its standard output to a device file that represents the screen, which can be displayed on the screen in this way. Shell also uses the device file that represents the keyboard as the source of standard input, so that the command receives as input anything you type on the keyboard.
1.2.3 redirect
Redirection refers to various ways to change the source of shell standard input and the direction of standard output. For example, by default, shell associates standard input from cat to the keyboard and standard output to the screen. But you can also have shell redirect the standard input or dimensioned output of any command by associating it with a command or file rather than with a device file that represents the keyboard or screen.
1. Redirect standard output
The output of the shell command can be redirected to the specified file instead of the screen by redirecting the symbol (>). The format of the command for redirection is:
Command [arguments] > filename
Where command is an executable program (such as an application or a tool), arguments is an optional parameter, and filename is the normal file name to which shell redirects output.
Redirection may overwrite the file! If the file already exists before the redirect command is executed, shell will rewrite and overwrite its original contents.
two。 Redirect standard input
Like redirecting standard output, you can also redirect standard input. By redirecting standard input symbols (test01 [root@QUFENGBIN test] # cat test01noclobber test
Redirect the output symbol followed by the pipe symbol, even if you use the symbol combination "> |" to ignore the setting of noclobber.
[root@QUFENGBIN test] # set-o noclobber [root@QUFENGBIN test] # echo "noclobber test" > test01-bash: test01: cannot overwrite existing file [root@QUFENGBIN test] # echo "noclobber test" > | test01 [root@QUFENGBIN test] # cat test01noclobber test [root@QUFENGBIN test] # set + o noclobber4. Append standard output to a file
Use the append output symbol (> >) to add new content to the end of a file without changing the existing content.
[root@QUFENGBIN test] # cat test01noclobber test [root@QUFENGBIN test] # echo "noclobber test" > test01; cat test01noclobber test [root@QUFENGBIN test] # echo "noclobber test" > > test01; cat test01noclobber testnoclobber test5./dev/null: make data disappear
The device / dev/null is a data receiver (data sink), often referred to as a bit bucket. You can redirect data that you don't want to see or save to / dev/null, so that the data will disappear without leaving a trace.
[root@QUFENGBIN test] # echo "noclobber test" > / dev/null
When you read the data from / dev/null, you get an empty string.
[root@QUFENGBIN test] # ls-l test01-rw-r--r-- 1 root root 30 Apr 28 14:59 test01 [root@QUFENGBIN test] # cat / dev/null > test01 [root@QUFENGBIN test] # ls-l test01-rw-r--r-- 1 root root 0 Apr 28 15:05 test011.2.4 Pipe
Shell uses pipes to connect the output of one command directly to the input of another. The function of a pipe (sometimes called pipeline) is similar to the process of redirecting the standard output of one command to a file and then using that file as standard input to another command. The pipeline does not process each command separately and does not require intermediate files. The symbol of the pipe is a vertical bar (|), and the command line syntax format is:
Command_a [arguments] | command_b [arguments]
The above command line gets the same result as the following set of commands:
Command_a [arguments] > tempcommand_b [arguments]
< temprm remp 任何Linux工具都可以使用管道从命令行上指定的文件中接受输入,也可以从标准输入接受输入。 有些使用管道的命令仅从标准输入接受输入,如工具tr(transtate,转换)就只能从标准输入接受输入(即tr只能通过标准输入接受输入,而无法通过命令行参数来接受输入)。 使用tr的最简单格式:tr string1 string2 tr工具从标准输入接受输入,查找与string1匹配的字符,找到一个匹配就将string1的字符替换为string2中对应字符。tr工具将它的输出发送到标准输出。 [root@QUFENGBIN test]# tr abc ABC < test01ABCdefgABCDEFG[root@QUFENGBIN test]# cat test01 | tr abc ABCABCdefgABCDEFG[root@QUFENGBIN test]# tr abc ABC test01tr: extra operand 'test01'Try 'tr --help' for more information. 1.过滤器 过滤器(filter)是将输入数据流处理后在输出数据流的一类命令。包含过滤器的命令行用一个管道将某个命令的标准输出连接到过滤器的标准输入,用另一个管道将过滤器的标准输出连接到另一个命令的标准输入。并不是所有的工具都可以用作过滤器。 2.tee:向两个方向输入 tee工具将标准输入复制到文件和标准输出。该工具被命名为tee是因为:它只有一个输入,但输出到两个方向。 [root@QUFENGBIN test]# who | tee who.out | grep rootroot tty1 2018-04-17 15:44root pts/0 2018-04-28 14:50 (111.113.5.18)[root@QUFENGBIN test]# cat who.outroot tty1 2018-04-17 15:44root pts/0 2018-04-28 14:50 (111.113.5.18)1.3 在后台运行程序 前台:当在前台运行命令时,shell将一直等到命令执行完毕。才会给出提示符使得你可继续输入下一个命令。当命令在后台运行时,就不必等待该命令完成,可直接输入另一个命令。 作业:作业(job)是由一个或者(可通过管道连接的)多个命令组成的序列。前台只能有一个作业位于窗口或屏幕中,但可以有多个作业在后台运行。同一时间运行多个作业是Linux的重要特性,这常被称为多任务特性。 作业编号与PID号:如果在命令行的末尾输入与符号(&)后回车,那么shell将在后台运行这个作业。同时,shell会给这个作业分配一个作业编号(是个小数字),并将其显示在方括号内。在作业编号之后,shell将显示进程标识(process identification,PID)号,该号是由操作系统分配的一个大数。每个大数后面都标识了后台运行的一条命令。然后,shell将显示另一个提示符,这是便可以键入另一个命令。当后台作业运行结束时,shell将显示一个消息,这个消息的内容为:已结束作业的作业编号和运行该作业的命令行。 1.将作业从前台移至后台 CONTROL+Z:程序挂起键,shell把前台的作业挂起(阻止其继续运行),并终止作业中的进程,将进程的标准输入与键盘隔开。用bg命令后跟作业编号可以把挂起的作业放到后台执行。如果仅有一个作业被挂起。那么可以不必指明作业编号。只有前台作业可以从键盘获得输入。为了将键盘和后台某个正运行的作业连接起来,必须把该后台作业移至前台。用fg命令后跟作业编号可以把后台的作业移至前台。不带任何参数的fg命令可以将后台唯一的作业移至前台。 2.kill:终止后台作业 命令行上输入kill后跟进程的PID号(或者后跟%和作业编号),可以将后台正在运行的进程(或作业)终止,使用中断键(通常CONTROL+C)是不能实现其功能的。 1.4 文件名生成/路径名展开 通配符和通配:当输入包含特殊字符(也称为元字符)的部分文件名时,shell可以生成与已有文件的名字匹配的文件名。这些特殊的字符也常常被称为通配符(wildcard)。当某个特殊字符作为参数出现在命令行上时,shell将该参数扩展为有序的文件名列表,并将列表传递给命令行上调用的程序。包含特殊字符的文件名称为模糊文件引用(ambiguous file reference),因为它们不与任何一个特定文件相关联。对这些文件名操作的过程称为路径名展开(path expansion)或者通配(globbing)。 1.4.1 特殊字符? 问号(?)是shell生成文件名的特殊字符,它与已有文件名中的某个单独字符匹配。 [root@QUFENGBIN test]# ls test0?test01[root@QUFENGBIN test]# echo wh?.outwho.out[root@QUFENGBIN test]# cat wh?.outroot tty1 2018-04-17 15:44root pts/0 2018-04-28 14:50 (111.113.5.18)1.4.2 特殊字符* 星号(*)的功能与问号的类似,不同之处在于,星号可以跟文件名中的任意多个(包括0个)字符匹配。 1.4.3 特殊字符[] 用方括号将一个字符列表括起来使得shell与包含列表中每个单独字符的文件名进行匹配。例如,test?可匹配test后跟任何一个字符的文件名,而方括号更严格些,test[01]仅与test0、test1匹配。这里,方括号定义了一个字符类(character class),该类由括号内的所有字符组成。 每个定义字符类只能替换文件名中的一个字符。方括号和其中的内容合起来的功能就如同问号一样,但是只能用字符类中的一个成员替换。 ps:左方括号后直接跟叹号(!)或脱字符(^)也可以定义字符类,该类与任何不在方括号内的字符匹配。例如,[^ab]*与不以a或b开始的文件名匹配。 [root@QUFENGBIN test]# lsaa ab ac ad ba bb bc bd cc dd[root@QUFENGBIN test]# ls *[^ab]ac ad bc bd cc dd[root@QUFENGBIN test]# ls [b-d]*ba bb bc bd cc dd 下面的例子表示ls工具不能翻译模糊文件引用。第一个ls命令带有参数aa*,shell将其扩展为匹配的文件名aa,并将该名字传递给ls。第二个命令将*转义,shell不再将*看作特殊字符,并将其传递给ls,ls报错。大多数工具和程序像ls一样也不能解释模糊文件引用,该解释工作由shell完成。 [root@QUFENGBIN test]# ls aa*aa[root@QUFENGBIN test]# ls aa\*ls: cannot access aa*: No such file or directory[root@QUFENGBIN test]# ls aaa*ls: cannot access aaa*: No such file or directory 注意:模糊文件引用由shell进行扩展,而不是shell调用的程序进行扩展。上面的例子都不能"看到"模糊文件引用。shell对模糊文件引用进行扩展,并将扩展得到的文件列表传递给工具。在下面的echo例子中验证了这一点,因为它显示了参数而不是模糊文件引用。 [root@QUFENGBIN test]# lsaa ab ac ad ba bb bc bd cc dd[root@QUFENGBIN test]# echo a?aa ab ac ad[root@QUFENGBIN test]# echo *aa ab ac ad ba bb bc bd cc dd[root@QUFENGBIN test]# echo a*aa ab ac ad[root@QUFENGBIN test]# echo .*. ..[root@QUFENGBIN test]# echo [a-m]*aa ab ac ad ba bb bc bd cc dd[root@QUFENGBIN test]# echo [x-z]*[x-z]*[root@QUFENGBIN test]# echo *[a-d]aa ab ac ad ba bb bc bd cc dd[root@QUFENGBIN test]# echo *[x-z]*[x-z][root@QUFENGBIN test]# echo [a-d]\*[a-d]*[root@QUFENGBIN test]# echo [x-z]\*[x-z]*1.5 内置命令(内建命令) 外部命令 外部命令,有时候也被称为文件系统命令,是存在于bash shell之外的程序。它们并不是shell程序的一部分。外部命令程序通常位于/bin、/usr/bin、/sbin或/usr/sbin中。ps是一个外部命令,你可以使用which和type命令找到它。 当外部命令执行时,会创建出一个子进程。这种操作被称为衍生(forking)。 内置命令(内建命令) 内建命令和外部命令的区别在于前者不需要使用子进程来执行。它们已经和shell编译成了一体,作为shell工具的组成部分存在。不需要借助外部程序文件来运行。可以利用 type 命令来了解某个命令是否是内建的。每个shell都有自己的内置命令集合。 输入命令"man bash",再输入命令"/^SHELL BUILTIN COMMANDS",shell将在内置命令部分搜索始于SHELL的行,从而可以查看内置命令的man页内容。 2、Bourne Again Shell 要点:初始化文件、重定向标准错误输出、编写简单的shell脚本、作业控制、操作目录栈、参数和变量、进程、命令历史机制、重新执行和编辑命令、别名、函数、控制bash特性和选项、处理命令行 Bourne Again Shell是一种命令解释器,同时也是一种高级编程语言。作为命令解释器,它们通过提示符响应并处理用户在命令行界面上输入的命令。而作为一种编程语言,它们将处理存放在所谓shell脚本文件中的命令。 2.1 shell基础 内容包括编写和使用初始化文件、重定向标准错误输出、编写和执行简单的shell脚本、命令分割和分组、实现作业控制和操作目录栈。 2.1.1 初始化文件 当启动shell时,它将运行初始化文件初始化自己。具体运行哪个文件取决于该shell是一个登录shell还是一个非登录shell的交互式shell(比如通过命令bash),又或者是一个非交互式shell(用来执行shell脚本)。要想运行初始化文件中的命令,用户必须具备读权限。 1.登录shell 登录shell本来就属于交互式shell。 /etc/profile:shell首先执行/etc/profile中的命令。通过设置这个文件,超级用户可以为全系统内的所有bash用户建立默认特征。 .bash_profile、.bash_login和.profile:然后shell依次查找~/.bash_profile、~/.bash_login和~/.profile,并执行它找到的首个文件中的命令。可以将命令放置在这些文件中的某个里以覆盖掉/etc/profile文件中的默认设置。 .bash_logout:当用户注销时,bash执行文件~/.bash_logout中的命令。这个文件包含了退出会话时需要执行的清理任务(比如删除临时文件)常用到的命令。 2.交互式非登录shell 在交互式非登录shell中并不执行前面提到的初始化文件中的命令。然而,交互式非登录shell从登录shell继承了由这些初始化文件设置的shell变量。 /etc/bashrc:尽管不是通过bash直接调用,许多~/.bashrc文件还是调用/etc/bashrc。这种安排使得超级用户可以为全系统内的非登录bash shell建立默认特性。 .bashrc:交互式非登录shell执行~/.bashrc文件中的命令,而登录shell的初始化文件(比如.bash_profile)通常会运行这个文件。这样,登录shell和非登录shell都可以使用.bashrc中的命令。 3.非交互式shell 非交互式shell(如那些运行shell脚本的shell)并不执行前面描述的初始化文件中的命令。然而,这些shell从登录shell那里继承了由这些初始化文件设置的shell变量。 BASH_ENV:非交互式shell查找环境变量BASH_ENV(或者当shell作为sh调用时为ENV),并执行由该变量命名的文件中的命令。 4.建立初始化文件 尽管有很多种初始化文件和shell,但是用户通常只需要主目录下的.bash_profile和.bashrc文件。.bash_profile中通过以下命令将为登录shell执行.bashrc(如果该文件存在)中的命令。 if [ -f ~/.bashrc ]; then . ~/.bashrcfi5..(句点)或者source:在当前shell中运行初始化文件 在编辑诸如.bashrc这类的初始化文件之后,要使这些修改起作用,用户没有必要注销然后再次登录,可以使用内置命令"."(句点)或者source(这是两个相同的命令)。与其他命令一样,在命令行上,"."后面必须有一个空格。内置命令"."或者source用起来类似于运行一个shell脚本,但是这些命令将该脚本作为当前进程的一部分运行。因此,当使用"."或者source运行脚本的时候,在脚本中改变的变量也将影响到运行该脚本的shell。可以使用"."或者source命令来运行任何shell脚本,而不仅仅是初始化文件,但是可能会带来副作用(比如可能修改用户依赖的shell变量的值)。如果将初始化文件作为常规shell脚本运行,并且不使用"."或source内置命令,那么启动脚本中创建的变量将只在运行该脚本的子shell中起作用。 2.1.2 符号命令Bourne Again Shell以多种方式使用符号(、)、[、]和$。为了避免混淆,下表列出了每种符号最通用的用法。 符号命令()子shell $()命令替换 (())算术表达式计算,let的同义词(当被括起来的值中包含等号时使用) $(())算术展开(不用于被括起来的值中包含等号的情形) []test命令 [[]]条件表达式,类似于[],但是添加了字符串比较 2.1.3 重定向标准错误输出 除了标准输出之外,命令还可以将输出发送到标准错误输出(standard error)。命令将错误消息发送到标准错误输出,这样就可以避免与发送到标准输出的信息混淆在一起。 与处理标准输出一样,默认情况下,shell 将命令的标准错误输出发送到屏幕上。除非将标准输出和标准错误输出中的某一个重定向,否则不能区分命令的输出到底是标准输出还是标准错误输出。 文件描述符:文件描述符(file descriptor)是程序发送输出和获取输入的地方。当执行一个程序时,运行该程序的进程打开了 3 个文件描述符,分别是:0(标准输入)、1(标准输出)和 2(标准错误输出)。重定向标准输出符号(>Is an abbreviation for 1 >, which tells shell to redirect standard output Similarly
< 是 0< 的简写,表示将标准输入重定向。符号 2>Redirect standard error output.
Here is an example:
When running cat, if one of the parameters does not exist and another file exists, cat sends an error message to the standard error output and copies a copy of the existing file to the standard output. Both messages will appear on the screen unless they are redirected.
[root@QUFENGBIN test] # cat yThis is y [root@QUFENGBIN test] # cat xcat: x: No such file or directory [root@QUFENGBIN test] # cat x ycat: x: No such file or directoryThis is y
When you redirect the standard output of a command, the output sent to the standard error output is not affected and still appears on the screen.
[root@QUFENGBIN test] # cat x y > holdcat: X: No such file or directory [root@QUFENGBIN test] # cat holdThis is y [root@QUFENGBIN test] # cat x y 1 > hold1 2 > hold2 [root @ QUFENGBIN test] # cat hold1This is y [root@QUFENGBIN test] # cat hold2cat: X: No such file or directory
Copy the file descriptor: in the next example, 1 > redirects standard output to the file hold. Then, 2 > & 1 declares that file descriptor 2 is a copy of file descriptor 1. As a result, both standard output and standard error output are redirected to the file hold.
Root@QUFENGBIN test] # cat x y 1 > hold 2 > & 1 [root@QUFENGBIN test] # cat holdcat: X: No such file or directoryThis is y
In the above example, 1 > hold comes before 2 > & 1. If they are reversed, the standard error output copies a copy of the standard output before the standard output is redirected to the file hold. In this way, only standard output is redirected to the file hold.
[root@QUFENGBIN test] # cat x y 2 > & 1 1 > holdcat: X: No such file or directory [root@QUFENGBIN test] # cat holdThis is y [root@QUFENGBIN test] # cat x y 2 > & 1cat: X: No such file or directoryThis is y
The redirection operators supported by Bourne Again Shell are shown in the following table.
The operator means filename unless the file filename already exists and the noclobber flag is set, the standard output will be redirected to the file filename. If the file filename does not exist and the noclobber tag is not set, the redirect operation creates the file > | filename redirects standard output to the file even though the file filename already exists and the noclobber tag is set. > > filename unless the file filename already exists and the noclobber tag is set, the standard output will be redirected to the file filename and the content will be added to the end of the original file. If the file filename does not exist and the noclobber tag is not set, the file is created & m copies standard output or file descriptor n (if n is specified in the command) [n] &-closes standard output or file descriptor n (if n is specified) 2.1.4 write a simple shell script
Shell scripts are files that contain shell executable commands. The command in the shell script can be any command that the user enters after the shell prompt. In addition to the commands you enter at the command line, shell scripts can also use control flow commands (also known as control structures). Use this set of commands to change the order in which the commands in the script are executed.
1.chmod: make files executable
Any user who wants to execute the file name as a command line must have execution access. If the file is a shel l script, the user must also have read access when trying to execute the file. Read access is not required when executing a binary executable (compiled program).
[root@QUFENGBIN test] # ll whoson-rw-r--r-- 1 root root 41 Apr 30 20:09 whoson [root@QUFENGBIN test] # cat whosondateecho "User Currently Logged In" who [root@QUFENGBIN test] # whoson-bash: whoson: command not found [root@QUFENGBIN test] #. / whoson-bash:. / whoson: Permission denied [root@QUFENGBIN test] # chmod uplix whoson [root@QUFENGBIN test] #. / whosonMon Apr 30 21:36:18 CST 2018User Currently Logged Inroot tty1 2018-04-17 15:44root pts/0 2018-04-30 11:55 (118.74.57.231) [root@QUFENGBIN test] # whoson-bash: whoson: command not found [root@QUFENGBIN test] # PATH=$PATH:. [root@QUFENGBIN test] # whosonMon Apr 30 21:36:53 CST 2018User Currently Logged Inroot tty1 2018-04-17 15:44root pts/0 2018-04-30 11:55! Specify shell
You can place a special string on the first line of the shell script file to tell the operating system which shell to use to execute the file. Because the operating system checks the opening string of the program before attempting the exec file, these characters save the operating system from making a failed attempt. If the first two characters of the script are #!, the system uses those characters after those two characters as the absolute pathnames of the command interpreter used to execute the script. It can be the pathname of any program, not just shell.
3.# start with one line of comment 4. Execute shell scripts (fork, exec, source)
Fork and exec system calls: after the user enters a command on the command line, shell will fork a new process to create a copy of the current shell process (child shell). This new process will attempt to exec (execute, execute) the command. Like fork, exec routines are executed by the operating system (system calls). If the command is a binary executable program, such as a compiled C program, then exec executes successfully, and the system calls the executable program to overwrite the newly created sub-shell. If the command is a shell script, exec execution fails. When exec fails, the command is assumed to be a shell script, and the child shell executes the commands in the script. Instead of logging in to shell to expect to read input from the command line, the sub-shell takes input from a file (shell script). So, if you don't have execute permission for the shell script file, the user can use the bash command to exec a shell to run the script directly, so that you can run the commands in the script.
Differences among 5.fork, exec and source
Fork (~ / test/test01.sh): if the shell contains an execute command, then the child command does not affect the parent command, and the parent command is executed after the child command has been executed. The environment variables of the child do not affect the parent.
Description: fork is the most common, that is, directly in the script with ~ / test/test01.sh to call test01.sh this script. At run time, a script is opened for sub-shell to execute the call, and parent-shell is still there when sub-shell executes. After the execution of sub-shell, return parent-shell. Sub-shell inherits environment variables from parent-shell, but environment variables in sub-shell do not bring back parent-shell.
Exec (exec ~ / test/test01.sh): after the child command is executed, the parent command is no longer executed.
Note: unlike fork, exec does not need to open a new sub-shell to execute the called script. The called script is executed in the same shell as the parent script. But after invoking a new script with exec, the content after the exec line in the parent script is no longer executed. This is the difference between exec and source.
Source (source ~ / test/test01.sh): continue to execute the parent command after executing the child command, while the environment variables set by the child will affect the environment variables of the parent.
Note: the difference with fork is that instead of opening a new sub-shell to execute the called script, it is executed in the same shell. So the variables and environment variables declared in the called script can be obtained and used in the main script.
[root@QUFENGBIN test] # chmod upright test01.sh [root@QUFENGBIN test] # chmod upright x test02.sh [root@QUFENGBIN test] # cat test01.shemale Becho Becho test01.sh:\ $An is $A "case $1 in exec) echo" using exec … " Exec. / test02.sh;; source) echo "using source …" . . / test02.sh;; *) echo "using fork by default …" . / test02.sh;; esacecho "PID for test01.sh after exec/source/fork:$$" echo "test01.sh:\ $An is $A" [root@QUFENGBIN test] # cat test02.shemale to bind bashecho "PID for test02.sh: $" echo "test02.sh get\ $Atropa from test01.sh" A=Cexport Aecho "test02.sh:\ $An is $A" [root@QUFENGBIN test] # / test01.shPID for test01.sh before exec/source/fork:1259test01.sh: $An is Busing fork by default … PID for test02.sh: 1260test02.sh get $AbigB from test01.shtest02.sh: $An is CPID for test01.sh after exec/source/fork:1259test01.sh: $An is B [root@QUFENGBIN test] #. / test01.sh execPID for test01.sh before exec/source/fork:1261test01.sh: $An is Busing exec... PID for test02.sh: 1261test02.sh get $AbigB from test01.shtest02.sh: $An is C [root@QUFENGBIN test] #. / test01.sh sourcePID for test01.sh before exec/source/fork:1262test01.sh: $An is Busing source... PID for test02.sh: 1262test02.sh get $AbeliB from test01.shtest02.sh: $An is CPID for test01.sh after exec/source/fork:1262test01.sh: $An is C2.2 parameters and variables
What are environmental variables?
Bash shell stores information about shell sessions and work environments (also known as environment variables) through a feature called environment variables (environment variable). This feature allows you to store data in memory, which can be easily accessed by one-pass programs or scripts that shell is running. In bash shell, environment variables are divided into two categories: global variables and local variables.
Global environment variable
Global environment variables are visible to shell sessions and all generated child shell. Local variables are visible only to the shell that created them. The Linux system sets some global environment variables before starting the bash session. System environment variables basically use all uppercase letters to distinguish them from those of ordinary users. To view global environment variables, use either the env command or the printenv command.
Variable
In shell, the shell parameter (shell parameter) is related to a value that the user can access, and there are several different shell parameters. The name of a parameter consists of letters, numbers, and underscores, often referred to as shell variables (shell variable), or simply variables (variable). The variable name must begin with a letter or an underscore, not a number.
User-created variables
The shell variable of a user command or assignment is called a user-created variable (user-created variable). The user can modify the value of a user-created variable at any time, or set it to read-only. You can also make user-created variables global. Global variables (also known as environment variables) can be accessed by any shell and other programs created from the original shell. There is a naming convention that global variables only use uppercase letters, while other variables are named in mixed case.
Keyword variable
Keyword shell variables (keyword shell variable, abbreviated as keyword variables) have a special meaning for shell. Their names are generally short and helpful to memory. When a user starts shell (such as logging in), shell inherits several keyword variables from the environment. HOME and PATH belong to such variables.
Position parameters and special parameters
The names of positional and special parameters are not like variable names. Among them, the names of most parameters consist of only one character (such as 1,? And #, etc.) and, like all other variables, usually precede their names with a dollar sign (such as $1, $? And $#) The values of these parameters reflect different aspects of the user's interaction with shell. At any time, each parameter in the line of command that the user enters will become the value of the location parameter (positional parameter). Users can access command-line parameters using positional parameters, which will be used when writing shell scripts. The built-in command set can be used to assign values to position parameters. Other frequently used shell script values, such as the name of the command that was last executed, the number of command-line arguments, and the state of the most recent command execution, are stored in special parameters (special parameter). Users cannot assign values to special parameters.
2.2.1 user-created variable / reference variable [root@aminglinux_01 ~] # person= Alex [root @ aminglinux_01 ~] # echo persona [root @ aminglinux_01 ~] # echo $personalex
The command echo $person displays the value of the variable person instead of $person, because $person is not passed to echo as an argument. Because $appears at the beginning of the name, shell recognizes that this is the name of a variable, substitutes the value of the variable, and passes the value to echo. The built-in command echo displays the value of the variable instead of its name, but echo will never know that the user used the variable when calling it
Quote $: if you enclose the first $in single quotation marks, you can prevent shell from substituting the value of the variable. Double quotation marks cannot prevent substitution (all characters between quotation marks will be substituted, including single quotation marks), while both single quotation marks and backslash symbols\ can prevent substitution.
[root@aminglinux_01 ~] # echo $personalex [root @ aminglinux_01 ~] # echo "$person" Alex [root @ aminglinux_01 ~] # echo'$person'$ persona [root @ aminglinux_01 ~] # echo\ $person$ persona [root @ aminglinux_01 ~] # echo "'$person'" 'alex' [root@aminglinux_01 ~] # echo "'\ $person'"'$person'
Spaces: double quotes do not prevent variable substitution, but you can turn off the special meaning of most other characters.
[root@aminglinux_01 ~] # person= "alex and jenny" [root@aminglinux_01 ~] # echo $personalex and jenny [root @ aminglinux_01 ~] # person=alex and jenny-bash: and: command not found
When referencing a variable that contains tabs and multiple contiguous spaces, you need to use quotation marks to retain those spaces. If the variable is not quoted, shell will compress the string of each white space character into a single space character before passing it to the tool:
[root@aminglinux_01 ~] # person= "alex and jenny" [root@aminglinux_01 ~] # echo $personalex and Jenny [root @ aminglinux_01 ~] # echo "$person" alex and jenny
Pathname expansion in assignment: when referencing a variable that contains special characters that are not quoted, all shell interprets those characters as special characters.
[root@aminglinux_01 test] # ls1.txt 2.txt alex.1 ex.2 [root @ aminglinux_01 test] # memo=alex* [root @ aminglinux_01 test] # echo $memoalex.1 alex.2 [root @ aminglinux_01 test] # echo "$memo" alex*
PS: the syntax $VARIABLE is a special case of ${VARIABLE}, which is more generic, enclosing variable names in ${}. Curly braces isolate variable names. Curly braces are necessary when concatenating a variable with a string:
[root@aminglinux_01 test] # PREF= counter[ root @ aminglinux_01 test] # WAY=$ PREFClock[ root @ aminglinux_01 test] # FAKE=$ PREFEIT [root @ aminglinux_01 test] # echo $WAY $FAKE [root @ aminglinux_01 test] # WAY=$ {PREF} clock[ root @ aminglinux_01 test] # FAKE=$ {PREF} feit [root @ aminglinux_01 test] # echo $WAY $FAKEcounterclock counterfeit
Bourne Again Shell uses special variables $1, $2, $3 up to $9 to refer to parameters on the command line through positional parameters. If you need to reference a parameter after the ninth, you must use curly braces: ${10}. The name of the command is saved in $0.
Unset: deleting variabl
2.2.2 variable attribute 1. Readonly: make the value of a variable unchangeable
You can use the built-in command readonly to ensure that the value of a variable is not changed.
[root@aminglinux_01 test] # person= jenny [root @ aminglinux_01 test] # echo $personjenny [root @ aminglinux_01 test] # readonly person [root @ aminglinux_01 test] # person=alex-bash: person: read-only variable
When you use the built-in command readonly without arguments, it displays a list of all read-only variables.
[root@aminglinux_01 test] # readonlydeclare-r BASHOPTS= "checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath" declare-ir BASHPIDdeclare-ar BASH_VERSINFO=' ([0] = "4" [1] = "2" [2] = "46" [3] = "2" [4] = "release" [5] = "x86_64-redhat-linux-gnu") 'declare-ir EUID= "0 "declare-ir PPID=" 1018 "declare-r SHELLOPTS=" braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor "declare-ir UID=" 0 "declare-r person=" jenny "2. Declare and typeset: assign attributes to variables the built-in commands declare and typeset (which are two names of the same command) can be used to set the properties and values of the shell variable. The following table lists five attributes.
Attribute meaning-a declares an array variable
-f declare a function name variable
-I declare an integer variable
-r declare the variable as read-only, or you can use readonly
-x output variable (set to global variable), or export
List variable attributes: if you don't have any parameters or options, the built-in command declare lists all shell variables. Run the set command without any arguments, and you get the same result. If the built-in command declare has an option but no variable name as an argument, the command lists all shell variables with the specified collection of properties.
2.2.3 keyword variable
Keyword variables can be inherited or declared and initialized when shell starts.
1. HOME: user home directory
By default, the user's home directory is the working directory after the user logs in. When users create their accounts, their home directory is already created, and the file name is stored in / etc/passwd.
[root@aminglinux_01 test] # grep root / etc/passwdroot:x:0:0:root:/root:/bin/bashoperator:x:11:0:operator:/root:/sbin/nologin
Code character (~): shell uses the value of HOME to expand the pathname, which uses the abbreviated form (generation character ~) to represent the user's home directory
[root@aminglinux_01 test] # CD [root @ aminglinux_01 ~] # pwd/ root [root @ aminglinux_01 ~] # echo ~ / root2. PATH: the path to the shell finder
When you enter an absolute or relative pathname into shell instead of a simple filename as a command, shell will find the executable file with the specified filename in the specified directory. If the file corresponding to the pathname does not exist, shell will report a "command not found" error. If the specified file exists but the user does not have permission to execute, or if the user does not have read and execute rights to the shell script, shell will report a "Permission denied" error.
If you use a simple file name as the command, shell searches certain directories to find the program the user wants to execute. Shell searches several directories for files that have the same name as the command and that the user has execute permissions (for compiled programs) or read and execute permissions (for shell scripts). The shell variable PATH controls these search paths.
[root@QUFENGBIN] # echo $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/local/mysql/bin:/usr/local/openssl/bin:/root/bin3. MAIL: where e-mail is saved
The variable MAIL contains the pathname of the file where the user's mail is saved. The file where the user's mail is saved is the user's mailbox, usually / var/spool/mail/name, where name is the user's login name. If MAIL is set but MAILPATH is not set, shell will alert the user when the message arrives at the file specified by MAIL.
The variable MAILPATH contains a list of file names separated by colons. If this variable is set, shell will alert the user when any of the files in the list change (such as when an email arrives). You can add a question mark (?) to any file name in the list. The question mark is followed by a message. If there is a new message, shell displays the message. It replaces the "you have mail" message that appears when a user logs in to the system because of mail.
The variable MAILCHECK specifies the amount (in seconds) at which shell checks for new messages. The default value is 60 seconds. If you set this value to 0, the shell will check for new messages before each prompt is displayed.
[root@QUFENGBIN ~] # echo $MAIL/var/spool/mail/root [root@QUFENGBIN ~] # echo $MAILPATH [root@QUFENGBIN ~] # echo $MAILCHECK604. PS1: user main prompt
The default prompt for Bourne Again Shell is a dollar sign ($). If you run bash as root, the prompt is #. The variable PS1 holds the prompt string that shell uses to prompt the user for a command. When the user modifies the value of PS1, the user's prompt changes.
[root@QUFENGBIN ~] # echo $PS1 [\ u @\ h\ W]\ $[root@QUFENGBIN ~] # PS1= "[\ u @\ h\ W\!] $" [root@QUFENGBIN ~ 7] $
The prompt displayed by PS1= "[\ u@\ h\ W!] $" is in the format [user@host directory event] $, where user is the user name, host is the hostname before the first period (.) in the local domain name, directory is the base name of the working directory, and event is the event number of the current command.
[root@QUFENGBIN ~ 11] $PS1= "\ h\ $" QUFENGBIN $PS1= "\ @\ u $" 10:45 AM root $PS1= "\ $" $the following table gives some PS1 symbols
Display of symbols at the prompt\ $if run as root, it is displayed as #, otherwise it is $
\ W the pathname of the working directory
\ W Base name of the working directory
\! Current event (history) number
\ d date displayed in the format "working day / month / date"
\ h hostname of the machine, excluding domain name
\ h full machine name, including domain name
\ U user name of the current user
\ @ current time displayed in "12 hours, AM/PM" format
\ t display the current time in 12-hour "HH:MM:SS" format
\ a display the current time in 24-hour "HH:MM" format
\ t display the current time in 24-hour "HH:MM:SS" format
5. PS2: user secondary prompt [root@QUFENGBIN ~] # echo $PS2 > [root@QUFENGBIN ~ 17] $echo 'hello world >!' hello world prompt! [root@QUFENGBIN ~ 18] $PS2= "next:" [root@QUFENGBIN ~ 19] $echo "hello worldnext: 2" hello world26. PS3: menu prompt, PS4: debug prompt [root@QUFENGBIN ~] # echo $PS3 [root@QUFENGBIN ~] # echo $PS4+7. IFS: separated input fields (participle)
The IFS (Internet Field Separator, internal field separator) shell variable specifies the characters used to separate parameters on the command line, with default values of space, tab, and newline characters. Regardless of the value of IFS, users can always use one or more spaces or tabs to separate different arguments on the command line, assuming that these characters are not referenced or escaped.
When assigning character values to IFS, these characters can also separate fields, but only when expanding. This command-line interpretation is called word splitting.
[root@QUFENGBIN ~] # a=x:y:z [root@QUFENGBIN ~] # cat $acat: x:y:z: No such file or directory [root@QUFENGBIN ~] # IFS= ":" [root@QUFENGBIN ~] # cat $acat: X: No such file or directorycat: y: No such file or directorycat: Z: No such file or directory
Shell divides all expanded words on the command line based on the delimiters found in IFS. If the expansion is not carried out, there will be no word segmentation.
[root@QUFENGBIN ~] # IFS= "p" [root@QUFENGBIN ~] # export VAR [root@QUFENGBIN ~] # aa=export [root@QUFENGBIN ~] # echo $aaex ort
Although multiple consecutive spaces or tabs are considered a delimiter, each occurrence is considered a delimiter whenever another field delimiter field appears.
8. CDPATH: expand the scope of cd
Using the CDPATH variable, the user can change the working directory to a directory that is not a subdirectory of the working directory by passing a simple file name as an argument to the built-in command cd.
If you do not set CDPATH, but simply specify a file name as a parameter to call cd, cd will look in the working directory for a subdirectory with the same file name as that parameter. If CDPATH,cd is set, the directory in the CDPATH list will search for subdirectories with the same filename as this parameter. If cd finds a subdirectory, that directory becomes the working directory.
If the working directory is not included in CDPATH and the search fails in CDPATH, then cd will search under the working directory. If you want cd to search the working directory first, you can use the empty string as the first item of CDPATH. The empty string is represented by two colons (::). If the argument to the built-in command cd is an absolute path-- starting with a slash (/)-- then shell does not consider CDPATH.
2.2.4 shell Special variable 2.3Special characters (to be added) character usage newline character start command execution; separate commands () group commands to sub-shell execution, or mark functions & execute commands in the background | Pipeline > redirect standard output > > append standard output
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.