Shell Basics Quick Start to understand the operating principle of shell

About Shell

Shell is a program written in C, it is the user to use Linux bridge. Shell is both a command language is a programming language.

Shell refers to an application, the application provides an interface through which the user interface to access the operating system kernel services.

Ken Thompson's sh is the first Unix Shell, Windows Explorer is a typical graphical interface Shell.

Shell operating principle

On Linux is an operating system in the strict sense, we call the core, but we average user is not using the core directly, but through the shell. That is, shell, comparison of Windows, a graphical interface that shell. A simple definition is the shell command line interpreter function is to translate the user's commands to the core processing, while the core processing of translation results to the user. It can be seen shell mainly for our instruction parsing, parsing instructions to the Linux kernel. Feedback results in a kernel operation results, to the user through parsing shell.

not personally execute shell commands in the interpretation of the time, but spawn child processes have the child process to complete this work, this benefit is the risk to others, when problems arise that executes instructions will not affect the shell (the impact the execution of other instructions). shell can not hang, shell once hung Nothing else can explain commands. For us shell in order to ensure the lowest risk themselves, to explain the work of the command line by creating a child process. And as long as their shell to wait on it.

Shell Script

Shell script (shell script), is a script written for the shell. Said shell industry usually refers to a shell script, but readers should know, shell and shell script are two different concepts.

Shell script interpreter

Linux Shell script interpreter of many species, a system there can be multiple shell script interpreter, you can cat /etc/shellsview the system installation shell script command interpreter.

/bin/sh

/bin/bash

/bin/rbash

Because bash free and easy to use, widely used in daily work. Meanwhile, Bash is the default most Linux systems Shell script interpreter.

head shell script, #! / bin / sh and #! / bin / bash difference.

GNU / Linux operating system / bin / sh This is a symbolic link to bash (Bourne-Again Shell), but in view of the bash too complicated, some people bash ported from NetBSD to Linux and changed its name to dash Debian Almquist Shell), and recommended / bin / sh points to it (soft), scripts for faster execution speed. Dash Shell Bash Shell than the much smaller, POSIX compliance.

sh一般设成bash的软链
在一般的linux系统当中(如redhat),使用sh调用执行脚本相当于打开了bash的POSIX标准模式
也就是说 /bin/sh 相当于 /bin/bash --posix
sh跟bash的区别,实际上就是bash有没有开启posix模式的区别

The first shell script

Create a new file test.sh, extension sh (sh behalf shell), the extension does not affect the script execution, see the name EENOW like.

Run Shell Script There are two ways:

1, as an executable program

cd to the appropriate directory:

chmod + x ./test.sh # the script has execute permissions ./test.sh # script execution

Attention must be written ./test.sh, rather than test.sh, run the other binary programs, too, write directly test.sh, linux PATH system will go in search of anyone named test.sh, and only / bin , / sbin, / usr / bin, / usr / sbin and so on in the PATH, your current directory is usually not in the PATH, so test.sh will not find written order, tells the system to use ./test.sh say , to find in the current directory.

2, as explained parameters

This mode of operation is run directly interpreter, its file name parameter is the shell script, such as:

/bin/sh test.sh

Shell Variables

Grammar rules: variable name = variable value my_name = "Gavin Pan"

Note that there is a space between the variable name and the equal sign, which may be familiar to you and all programming languages ​​are not the same. At the same time, variable naming names and other similar language can not be used in bash keyword (help command to view the available reserved keywords).

1. Variable Types

Local variables: local variables defined in the script or command, only valid in the current shell instance, start the other shell program can not access local variables.

Environment Variables: All procedures, including the shell is started, can access environment variables, some programs require environment variables to ensure their normal operation. It can be used the set command to view the current environment variables.

shell variables: Special variable set by the shell program. shell variable environment variable part is, in part, local variables, to ensure the normal operation of the shell.

2. Define the variables

my_name="Gavin Pan"

3. The reference variable

echo $my_name
echo ${my_name}
#引用一个定义过的变量,只要在变量名前面加$即可,变量名外面的花括号是可选的,加不加都行,加花括号是为了帮助解释器识别变量的边界。

4. Re-defined variables

my_name = "Gavin"

my_name="Gavin Pan"

5. Read-only variables

Use readonly command variable becomes read-only variables

my_name = "Gavin"
readonly my_name
my_name="Gavin Pan"

6. Delete variables

my_name="Gavin"
unset my_name
echo $my_name

Use the unset command to remove variables can not be used again after the variable is deleted, while the unset command can not remove the read-only variables.

Shell string

String shell programming is the most common and useful type of data (except numbers and strings, but also other types of handy lacks), the string enclosed in single quotes, double quotes may be used, it may be practiced without quotes. The difference between single and double quotation marks are similar with PHP.

str1='hello Gavin'
str2="hello Gavin"
str3="hello \"$my_name\"
echo str1 #hello Gavin
echo str2 #hello Gavin
echo str3 #hello "Gavin Pan"

The advantages of double quotes: There can be variable, you can escape character.

String related operations

#拼接字符串
a="a"
b="b"
c=$a$b 或者 c="$a $b"
获取字符串长度
str="abcdefg"
echo ${#str} #output 7
提取字符串
echo ${str:1:3} #output bcd
以上例子表示从字符串的第二个数字往后截取3个字符
查找字符串
echo `expr index "$str" cb` #output 2
注意: 以上脚本中 ` 是反引号,而不是单引号 ',不要看错了哦。
查找字符 c 或 b 的位置(哪个字母先出现就计算哪个)

shell array

In the Shell, with parentheses for the array, the array element divided by the "space" symbol. The general form of an array defined as: array name = (value 1 value 2 ... value n) , for example:

array_name=(value0 value1 value2 value3)
或者
array_name=(
value0
value1
value2
value3
)
还可以单独定义数组的各个分量:
array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen

May not be used continuously subscripts and subscript range is not limited. The general format of the reading array reads array element value is: $ {array name [index]} example:

valuen=${array_name[n]}
使用 @ 符号可以获取数组中的所有元素,例如:
echo ${array_name[@]}
获取数组的长度
获取数组长度的方法与获取字符串长度的方法相同,例如:
取得数组元素的个数
length=${#array_name[@]}
或者
length=${#array_name[*]}
取得数组单个元素的长度
lengthn=${#array_name[n]}

shell parameter passing

echo "Shell 传递参数实例!";
echo "执行的文件名:$0";
echo "第一个参数为:$1";
echo "第二个参数为:$2";
echo "第三个参数为:$3";
执行结果如下
$ chmod +x test.sh 
$ ./test.sh 1 2 3
Shell 传递参数实例!
执行的文件名:./test.sh
第一个参数为:1
第二个参数为:2
第三个参数为:3

shell special characters

$ # Number of arguments passed to script $ * displays all current process parameters passed $$ script to script an ID number to a single string $! $ @ And $ ID number the last process running in the background * the same, but when you add quotes, each parameter and returns $ in quotation marks? display the exit status of the last command. 0 means no error, any other value indicates an error

$ * And $ @ difference: the same point: that all parameters are passed to represent the script. Differences: not "" included, $ and $ @ parameters are the composition of the list with $ 1 $ 2 ... $ n the form. Is "" included, "$ " resets all of the parameters as a whole, to "$ 1 $ 2 ... $ n-'form to form a whole string;" "Separately will each parameter to" $ @ $ 1 "" $ 2 " ... in the form of "$ n" composed a list of parameters.

basic operators shell

Arithmetic operators

Native bash does not support simple mathematical operations, but can be achieved through other commands, such as awk and expr, expr most commonly used.

expr is an expression calculation tool, use it to complete the evaluation of an expression operation.

a=1
b=2
val=`expr $a + $b`

Note that the spaces around the operator to have a special call to remember the multiplication sign in front \, the other no difference.

Relational Operators

Relational operator support only numeric, string is not supported, unless the value of the string is a number.

-eq detecting two numbers are equal, returns true equal. [$ A -eq $ b] returns false. -ne detecting two numbers are not equal, not equal Returns true. [$ A -ne $ b] returns true. -Gt detect whether the number is greater than the right to the left, and if so, it returns true. [$ A -gt $ b] returns false. -lt detect the left of the number is less than the right, and if so, it returns true. [$ A -lt $ b] returns true. Detecting whether the number -ge greater than or equal to the left of the right, if so, returns true. [$ A -ge $ b] returns false. -Le detecting whether the number is less than or equal to the right of the left, and if so, it returns true. [$ A -le $ b] returns true.

Boolean operators

! NOT operation, the expression is true returns false, true otherwise. [! False] returns true. -o or operation, there is an expression that returns true then is true. [$ A -lt 20 -o $ b -gt 100] return true. -a and operations, the two expressions return true is true only. [$ A -lt 20 -a $ b -gt 100] return false.

Logical Operators

&& logical AND [[$ a -lt 100 && $ b -gt 100]] Back to false || logical OR [[$ a -lt 100 || $ b -gt 100]] Returns true

String operators

= Detects two strings are equal, returns true equal. [$ A = $ b] returns false. ! = Detects whether two strings are equal, not equal Returns true. [$ A! = $ B] returns true. detecting whether the string length -z 0, 0 returns true. [-Z $ a] returns false. -n is 0 string length is detected, not zero returns true. [-N "$ a"] returns true. $ Detects whether the string is empty, do not return true empty. [$ A] returns true.

a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a 等于 b"
else
   echo "$a = $b: a 不等于 b"
fi
if [ $a != $b ]
then
   echo "$a != $b : a 不等于 b"
else
   echo "$a != $b: a 等于 b"
fi
if [ -z $a ]
then
   echo "-z $a : 字符串长度为 0"
else
   echo "-z $a : 字符串长度不为 0"
fi
if [ -n "$a" ]
then
   echo "-n $a : 字符串长度不为 0"
else
   echo "-n $a : 字符串长度为 0"
fi
if [ $a ]
then
   echo "$a : 字符串不为空"
else
   echo "$a : 字符串为空"
fi

执行脚本,输出结果如下所示:

abc = efg: a 不等于 b
abc != efg : a 不等于 b
-z abc : 字符串长度不为 0
-n abc : 字符串长度不为 0
abc : 字符串不为空

File Test Operators

-B file whether the file is a block device file is detected, and if so, it returns true. [-B $ file] returns false. -C file whether the file is a character device file is detected, and if so, it returns true. [-C $ file] returns false. -D file to detect whether a file is a directory, and if so, it returns true. [-D $ file] returns false. -F file to detect whether a file is an ordinary file (neither catalog nor the device file), and if so, it returns true. [-F $ file] returns true. -G file to detect whether a file has the SGID bit, and if so, it returns true. [-G $ file] returns false. -K file to detect whether a file has the sticky bit (Sticky Bit), and if so, it returns true. [-K $ file] returns false. -P file to detect whether a file is named pipe, and if so, it returns true. [-P $ file] returns false. -U file file to detect whether the SUID bit, and if so, it returns true. [-U $ file] returns false. Detecting whether -r file readable file, if so, it returns true. [-R $ file] returns true. Whether -w file detect file can be written, and if so, it returns true. [-W $ file] returns true. -X file executable files to detect whether, and if so, it returns true. [-X $ file] returns true. Detecting whether the file is empty -s file (whether the file size is greater than 0), is not empty return true. [-S $ file] returns true. -e file test documents (including directory) exists, and if so, it returns true. [-E $ file] returns true.

file="/test.sh"
if [ -r $file ]

shell flow control

if condition
then
	command
fi
if condition
then
command
else
commandN
fi
if condition
then
command
elif confition2
then
command2
else
cpmmandN
fi
for loop in 1 2 3 4 5
do
echo $loop
done
while condition
do
command
done
until condition
do
command
done
与while正好相反
echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac

Guess you like

Origin www.cnblogs.com/gavinpan/p/11236006.html