Shell Programming Basics (i)

Source: Internet
Author: User
Tags arithmetic shebang

First, Shell history

The role of the shell is to explain the execution of the user's commands, the user enters a command, the shell interprets the execution of one, which is called Interactive (Interactive), and the shell has a way of executing the command called batch processing. The user writes a shell script in advance, with a number of commands that allow the shell to execute the commands at once without having to hit the command one at a time. Shell scripts are similar to programming languages, and there are variables and process control statements, but shell scripts are interpreted and do not need to be compiled, and the shell program reads and executes the commands from a single line of script, which is equivalent to a user knocking a line of commands from the script to the shell prompt for execution.

For historical reasons, there are many kinds of shells on UNIX systems:

1.sh (Bourne Shell): Developed by Steve Bourne, various Unix systems are equipped with SH.

2.CSH (C Shell): Developed by Bill Joy and released with BSD UNIX, its Process control statements are much like the C language and support many features that Bourne Shell does not support: Job control, Command history, command-line editing.

3.ksh (Korn Shell): Developed by David Korn, backwards compatible with SH, and added new features introduced by CSH, is the Shell of many Unix system standard configurations, on which/bin/sh is often a symbolic link to/bin/ksh.

4.TCSH (Tenex C Shell): is an enhanced version of CSH, the introduction of command completion, in the FreeBSD, Mac OS X and other systems to replace the CSH.

5.bash (Bourne Again Shell): The shell developed by GNU, the main goal is to be consistent with the POSIX standard, while taking into account the compatibility of SH, bash from CSH and Ksh learn a lot of features, is a variety of Linux distribution standard configuration of the shell, /bin/sh on Linux systems are often symbolic links to/bin/bash. However, bash and SH are a lot different, on the one hand, bash expands some commands and parameters, on the other hand, bash is not completely compatible with SH, some behaviors are inconsistent, so bash needs to simulate the behavior of SH: when we start bash through the program name SH, Bash can pretend that it is sh, does not recognize the extended command, and behaves the same as SH.

The 6.ZSH command complement function is very powerful, can fill the path, complete the command, complete parameters and so on.

vim/etc/passwd The last column shows the user's corresponding shell type

Root:x:0:0:root:/root:/bin/bash
Bin:x:1:1:bin:/bin:/sbin/nologin
Daemon:x:2:2:daemon:/sbin:/sbin/nologin
Adm:x:3:4:adm:/var/adm:/sbin/nologin
Lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
Sync:x:5:0:sync:/sbin:/bin/sync
Shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
Halt:x:7:0:halt:/sbin:/sbin/halt
Mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

After the user enters a command at the command line, the shell typically fork and exec the command, but the shell's built-in command is the equivalent of invoking a function in the shell process and does not create a new process. Previously learned CD, alias, Umask, exit and other commands are built-in commands, usually with the which command can not find the location of the program File command is built-in command, built-in command does not have a separate man manual, to view the built-in command in the man manual, should

$ mans Bash-builtins

such as export, shift, if, eval, [, for, while, and so on. The built-in command does not create a new process, but it also has the exit status, usually with 0 to indicate that a success nonzero indicates a failure, although the built-in command does not create a new process, but there is a status code after execution, or it can be read with a special variable of $.

Second, execute the script

Write a simple script test.sh:

[email Protected]_0_5_centos test]# VI test.sh The following is the content in test.sh #!/bin/SHCD: LS

The shell script uses # notation, which corresponds to the C//comment. However, if # is at the beginning of the first line and is #! (called shebang), the exception is that the script uses the interpreter specified later/bin/sh interpret execution. If you add this script file with executable permissions and then execute:

4-rw-r--r--1 root root 14:28 test.sh[[email protected]_0_5_centos test]# chmod a+x test.sh[[email Protected]_0_5_centos test]#. /test.shbin  boot  data  dev  etc  Home  install  Lib  lib64  lost+ Found  media  mnt  opt  proc  root  run  sbin  software  SRV  sys  test  tmp  usr  var

The shell will fork a child process and call exec to execute it./test.sh this program, the EXEC system call should replace the code snippet of the process with the code snippet of the./test.sh program and execute it from its _start. However, test.sh is a text file, there is no code snippet and _start function, how to do? In fact, Exec has another mechanism, if you want to execute a text file, and the first line specifies the interpreter with Shebang, then replace the current process with the code snippet of the interpreter program and execute it from the _start of the interpreter, and the text file is passed to the interpreter as a command-line argument. Therefore, executing the above script is equivalent to executing the program

[Email Protected]_0_5_centos test]#/bin/sh./test.sh

Executing in this manner does not require the test.sh file to have executable permissions.

If you enclose commands entered under the command line in parentheses, you will also fork out a sub-shell to execute the command in parentheses, where you can enter multiple commands separated by semicolons, such as:

[Email Protected]_0_5_centos test]# (CD.; LS-L)

The effect of executing shell scripts with the above two methods is the same, CD: Command changes the PWD of the child shell without affecting the interactive shell. However the order

[Email protected]_0_5_centos test]# CD ...; Ls-l

Then there are different effects on the CD. Commands are executed directly under the interactive shell, changing the pwd of the interactive shell, but this is equivalent to executing the shell script:

[Email Protected]_0_5_centos test]# source./test.sh or [email protected]_0_5_centos test]#. ./test.sh

The source or. command is the shell's built-in command, which does not create a child shell, but rather executes the commands in the script line-by-row under the interactive shell.

Iii. basic Syntax 1, variables

As a rule, shell variables consist of all caps and underscores, and there are two types of shell variables:

1. Environment variables

Environment variables can be passed from the parent process to the child process, so the environment variables of the shell process can be passed from the current shell process to the forked child process. Use the PRINTENV command to display the environment variables for the current shell process.

2. Local Variables

exists only in the current shell process, with the SET command to display all variables (including local variables and environment variables) and functions defined in the current shell process.

Environment variables are concepts that are present in any process, and local variables are shell-specific concepts. In the shell, environment variables and local variables are defined and used similarly. Define or assign a variable to a shell:

[Email Protected]_0_5_centos test]# varname=mmzsit

Note that there can be no spaces on either side of the equal sign, or it will be interpreted by the shell as command and command line arguments.

A variable is defined only in the current shell process, it is a local variable, the export command can be exported to the local variables as environment variables, defining and exporting environment variables can usually be completed in one step:

[Email protected]_0_5_centos test]# Export Varname=mmzsit

It can also be done in two steps:

[Email protected]_0_5_centos test]# varname=mmzsit[[email protected]_0_5_centos test]# export VARNAME

You can use the unset command to delete a defined environment variable or local variable.

[Email protected]_0_5_centos test]# unset VARNAME

If a variable is called VARNAME, it can be represented by ${varname}, and its value can be expressed in $varname without ambiguity. The differences between the two representations are compared by the following example:

[email Protected]_0_5_centos test]# echo $SHELL/bin/bash

Note that when you define a variable, you do not use $ when you take the variable value. Unlike the C language, shell variables do not need to be explicitly defined types, in fact the values of shell variables are strings, such as we define VAR=45, in fact, the value of Var is a string 45 instead of an integer. The shell variable does not need to be defined before it is used, and the value is an empty string if a variable is not defined.

2. File name Substitution (Globbing): *? []

The characters used for matching are called wildcards (Wildcard), as follows:

wildcard characters *   match 0 or more of any characters ?   Matches an arbitrary character [several characters]  matches any one character in square brackets  /mmzs/tt*$ ls ch0?. doc$ ls ch0[0-2].doc$ ls ch[012]   [0-9].doc

Note that the file name that globbing matches is expanded by the shell, which means that the parameter has been expanded before it is passed to the program, such as the LS ch0[012].doc command above, If the current directory has Ch00.doc and Ch02.doc, the parameters passed to the LS command are actually the two file names instead of a matching string.

3. Command substitution: ' or $ ()

It is also a command that is enclosed in quotation marks, and the shell executes the command first, and then the output is immediately substituted to the current command line. For example, define a variable to hold the output of the date command:

[Email protected]_0_5_centos test]# date=14:43:31 CST 2018

Command substitution can also be expressed in $ ():

[Email protected]_0_5_centos test]# date=14:44:04 CST 2018
4. Arithmetic substitution: $ (())

For arithmetic calculations, the value of the shell variable in $ (()) is converted to an integer, the same meaning as the $[] equivalent for example:

[[Email Protected]_0_5_centos test]# var=4 [[email Protected]_0_5_centos test]# Echo ${var}4[email Protected]_0_5_centos test]# Echo $ (($VAR+3))7$ (()) can only be used with the +-*/and () operators, and can only do integer operations.  $[base#n], where base represents the binary, n is interpreted as base, followed by an operand, interpreted in decimal. 




21st
5. Escape character \

Similar to the C language, \ is used as an escape character in the shell to remove the special meaning of a single character immediately following it (except for a carriage return), in other words, the literal value of the character immediately followed. For example:

[email Protected]_0_5_centos test]# echo $SHELL/bin/bash[[email protected]_0_5_centos test]# Echo \$ Shell$shell[[email Protected]_0_5_centos test]# echo \ \

For example, create a file named "$ $" to do this:

4-rw-r--r--1 root root  0 Jul 14:50 $ $-rwxr-xr-x 1 root root 14:28 test.sh

There is also a character that does not have a special meaning, but it is cumbersome to use it as a filename. This is not possible if you want to create a file with a filename that begins with the-number:

[Email protected]_0_5_centos test]# Touch--' z ' for more information. even adding \ Escaping is an error: [Email protected]_0_5_centos test]# Touch \---' z ' for more information.

Because the various UNIX commands take the command line arguments that begin with the-number as an option for the command, not as a file name. If you do not want to process a file name that begins with a-number, there are two ways to do this:

[Email Protected]_0_5_centos test]# touch./-Mmzs// or [email protected]_0_5_centos test]# Touch---Mmzs

\ There is also a use, after \ hit Enter to indicate the continuation of the line, the shell will not immediately execute the command, but instead of moving the cursor to the next line, a continuation prompt, waiting for the user to continue to input, and finally all the continuation of the line as a command to execute. For example:

Output ofthe >-l command)
6, single and double quotation marks

Unlike the C language, the single and double quotes in shell scripts are the same as the delimiter of the string, not the delimiter of the character.

1), single quotation marks are used to keep the literal value of all characters within the quotation marks, even if the \ and carriage returns within the quotation marks are no exception, but the single quotation marks cannot appear in the string;

2), enclosed in double quotes, will be treated as a single string, which prevents wildcard expansion, but allows variable expansion. This is different from the way single quotes are handled.

3), if the quotation mark does not match the input enter, the shell will give the continuation prompt, asks the user to enclose the quotation mark to match. For example:

[[Email Protected]_0_5_centos test]# echo ' $DATE '"$DATE"14:44:04 CST 2018 The variables in double quotes will be displayed, The contents of the single quotation mark are output as-is [[email Protected]_0_5_centos test]# echo' $DATE+123 ' $DATE +123 "$DATE +123"  14:44:04 CST 2018+123' 456\ (carriage return) > 123 ' (Press ENTER again to end the command)456123 "456\ (carriage return) > 123" (Press ENTER again to end the command) 456123

Shell Programming Basics (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.