One of the Linux--shell script notes.

Source: Internet
Author: User

Shell Scripts (1)

a Shell script is a special application that receives the operation commands entered by the user and interprets them, passes the actions that need to be performed to the kernel execution, and outputs the execution results. You can view the shell types supported by the current system in the/etc/shells file .

[[Email protected]~]# cat/etc/shells

/bin/sh

/bin/bash

/sbin/nologin

/bin/tcsh

/bin/csh

/bin/ksh

where /bin/bash is the default shell currently used by most Linux versions, all known as Bourne Againshell

Two ways to execute scripts

I./first.sh This method of execution requires a execute permissionto the first.sh script: Chomod+x first.sh

Second,sh/first.sh This execution method does not need to give first.sh script Execute permission, also can pass Source "." Execution

. first.sh or source/first.sh (there are spaces in the middle)

redirection and pipeline operations

Standard input ( STDIN): Default: Keyboard file number is 0

Standard Output ( STDOUT): Default: Monitor file number is 1

standard Error ( STDERR): Default: Monitor file number is 2

Redirected output > and >> are overlay and append redirects, respectively

REDIRECT input <

Redirect input can be used to create a password for a user

[Email protected]~] #vim Shelltest/useradd

123456

: X

[Email protected]~]# passwd--stdin Jerry <shelltest/useradd

Changingpassword for user Jerry.

Passwd:all authentication tokens updated successfully.

This saves you from having to enter the password multiple times when creating a password.

Error redirection 2> and 2>> are overrides and append redirects

when a command includes error output and standard output, you can use &> to output the standard and error to a file.

If you want to automatically compile and install httpd , you should point the make made install operation to/dev/null

[Email protected]~]# vim httpd.sh

#!/bin/bash

#httpdshell Install

cd/var/ftp/pub/httpd-2.2.17/

./config--prefix=/usr/local/httpd--enable-so &>/dev/null

Make&>/dev/null

Makeinstall $>/dev/null

..... the following ellipsis

after executing this script, compiling the installation will point out all the output files to /dev/null .

pipe symbol "| The result of the command output on the left side of the pipe character will be the input to the right command.

If you view the user name with "/bin/bash" as the shell, you can further filter with the awk command to display only the user name and login Shell column

The entire line is displayed before filtering

[Email protected]~]# grep "/bin/bash$"/etc/passwd

Root:x:0:0:root:/root:/bin/bash

Jerry:x:500:500::/home/jerry:/bin/bash

only user name and login shell are displayed after filtering

[Email protected]~]# grep "/bin/bash$"/etc/passwd | Awk-f: ' {print$1,$7} '

Root/bin/bash

Jerry/bin/bash

The purpose of awk above is to output column 1 and column7 for delimiters, and-F is the specified delimiter, which can be any character in the document, The default is delimited by a space or tab (the contents in curly braces are enclosed in single quotes).

Use Shell variables

Common Shell variables include: Custom variables, environment variables, predefined variables, positional variables.

a custom variable is a variable that is defined by the system user and is only valid in the user's own shell environment, so it is called a local variable.

The basic format for defining variables is " variable name = Variable Value ", and there are no spaces on either side of the equals sign. Variable names need to start with a letter or underscore, and do not include special characters in the name.

The custom variables are as follows:

[Email protected] ~]# System=centos

[Email protected] ~]# version=6.5

use echo echoing when viewing , add $ symbol before variable name

[Email protected] ~]# echo $system

Centos

[Email protected] ~]# echo $system $version

CentOS 6.5

When you echo the variable name, if there are other characters in the back that need to be surrounded by the curly braces '{}' , you will not be able to determine the correct variable name. Undefined variable that will be displayed as a null value.

[[email protected] ~]# echo $system 6.5 # due to undefined $system 6 It is only displayed . 5 variable value is empty

.5

[Email protected] ~]# echo ${system}6.5

centos6.5

Special actions for assigning values to variables

Specifying variable content directly after the equals sign is the most basic way to assign a value to a variable, and there are special assignment operations that give you the flexibility to assign variables for complex management tasks.

1. double quotation marks ("")

For example, when we include spaces in an assignment, we must enclose them in double quotation marks, as follows

[[email protected] ~]# centos=centos6.5 error assignment hint without this command

-bash:6.5:command not found

[[Email protected] ~] #Centos = "Centos 6.5"

[Email protected] ~]# echo $Centos

Centos 6.5

2.($) symbol

within the double quotation mark range, use the "$" symbol to refer to the values of other variables, as follows

[Email protected] ~]# redhat= "Red hat$version"

[Email protected] ~]# echo $redhat

Red Hat 6.5

3. single quotation mark (')

when the content to be assigned contains a special meaning character such as $,",\, and so on, it should be enclosed in single quotation marks, within the range of single quotes, other variable values cannot be referenced, and any character is treated as a normal character. However, when you include single quotes in the assigned content, you need to escape with the "\" symbol to avoid collisions. as follows

[Email protected] ~]# redhat= ' Red Hat $version '

[Email protected] ~]# echo $redhat

Red Hat $version

4. anti-apostrophe (')

The inverse apostrophe is primarily used for command substitution, allowing the output of a command to be assigned to a variable, and the backslash must be a command line that can be executed, otherwise an error occurs. as follows

[[email protected] ~]# ls-ld ' which service '

-rwxr-xr-x 1 root root 1744 2009-07-13/sbin/service

The above command is equivalent to executing the which service first and then viewing the file attributes equivalent to executing two consecutive commands.

However, you cannot use the backslash to implement a nested command substitution operation in a single line of commands, and you can use "$ ()" Instead of the anti-apostrophe to resolve a nested problem, such as the location of the configuration file where you view the package installation of the Useradd command program, as follows

[[email protected] ~]# RPM-QC $ (RPM-QF $ (whichuseradd))

/etc/default/useradd

/etc/login.defs

5.read Command

The Read command is used to prompt the user to enter information, thus enabling a simple interaction process, assigning the user input to the specified variable, assigning the extra content to the last variable, and assigning the entire row to the variable if there is only one specified variable. The following action waits for the user to enter and assigns the user input to the variable

[email protected] ~]# Read dir

/opt/backup

[Email protected] ~]# echo $dir

/opt/backup

The Read command can also set the prompt message with the "-P" option, as follows

[[email protected] ~]# read-p " Please specify the storage directory for the backup:" dir

Please specify a storage directory for the backup:/opt/backup/

[Email protected] ~]# echo $dir

/opt/backup/

It has been said that custom variables can only be used in their own shell to be called local variables, in fact we may change the local variables into global variables. As follows.

[Email protected] ~]# echo "$system $version"

CentOS 6.5

[[email protected] ~]# Export System version # set to global variable

[[email protected] ~]# Bash # into the child shell Environment

[Email protected] ~]# echo "$system $version"

CentOS 6.5

Export can also be created directly as a global variable when creating variables such as the following

[Email protected] ~]# exportfqnd= "www.baidu.com"

[Email protected] ~]# bash

[Email protected] ~]# echo $fqnd

Www.baidu.com

5. Numeric variable operation

EXPR is used for simple integer operations in the shell

There must be at least one space between the operator and the variable.

Expr variables 1 operator variable 2 [ operator variable 3] ...

Operators include the following types of

+: Addition -: Subtraction \*: Multiplication /: Division %: Take remainder operation

such as x=5 y=3

[Email protected] ~]# x=5

[Email protected] ~]# y=3

[Email protected] ~]# expr $x% $y

2

Environment variables of special variables

the environment variable refers to a class of variables that need to be created in advance by the Linux system, primarily for setting up the user's working environment, such as the host directory, the command lookup path, the user's current directory, and so on. Use env to view environment variables in the current working environment.

[Email protected] ~]# env |more

Hostname=localhost.localdomain

version=6.5

Term=linux

Shell=/bin/bash

histsize=200

Kde_no_ipv6=1

................. omitted

Path is the default search path for setting executable programs. As first.sh can be added under /root/ , the following

[[Email protected] ~] #PATH = "$PATH:/root"

[Email protected] ~]# echo $PATH

/usr/lib/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/ Usr/bin:/root/bin:/root

in the The global configuration file for environment variables in Linux is/etc/profile, and thevariables defined in this file act on all users, and each user has their own separate configuration file (~/.bash_profile). If the change history order is changed from 20 to

[[Email protected] ~] #vim/etc/profile

...// omitted

Histsize=20

[[email protected] ~]# Source/etc/profile make its configuration effective

[Email protected] ~]# history |wc–l

20

Position variables of special variables

Positional variables when you execute a command script, the first field represents the command name or script name, and the remaining string parameters are assigned to the positional variable sequentially from left to right, as follows

[Email protected] ~]# VI export.sh

#!/bin/bash

######## Position variable operation script #######

sum= ' Expr $ \*

echo "$ \* = $SUM"

[[Email protected] ~]# SH expr.sh 5 6

5 \* 6 = 30

Pre-defined variables of special variables

A predefined variable is a defined variable that a user cannot manually create or assign directly to a predefined variable.

Common pre-defined variables

$#: Indicates the number of positional parameters in the command line

$*: Represents the contents of all positional parameters

$? : Indicates the state after the last command was executed and returns 0 for the correct other value is an exception

$ A: represents the currently executing script or program name


This article is from the "Addiction" blog, make sure to keep this source http://luoyuxiangnian.blog.51cto.com/6214813/1550510

One of the Linux--shell script notes.

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.