Shell scripting basics, using variables, conditional testing and selection, and list-looping

Source: Internet
Author: User
Tags chmod stdin

Shell language

Script: Can run, a file, can implement some function (command stacking)

[Email protected] ~]# vim/root/stu.sh

echo Hello World
Cat/etc/redhat-release
Uname-r
Hostname
Ifconfig | Head-2

[Email protected] ~]# chmod +x/root/stu.sh

[Email protected] ~]#/root/stu.sh

Case 1: Writing a script to create a user

[Email protected] ~]# vim/root/user.sh

Useradd nsd02
Echo 123 | passwd--stdin nsd02

[Email protected] ~]# chmod +x/root/user.sh

[Email protected] ~]#/root/user.sh

#################################################################

Standardize the general composition of shell scripts
? #! Environment Declaration (all of the following statement interpreters)
? # comment Text
? Executable code

Pipeline Delivery
? Use | Pipeline operation
– The standard output from the previous command is given to the latter command to process

REDIRECT Output

: Collect only the correct output from the previous command
2>: Collect only the error output from the previous command
&>: Front command correct and error output

[Email protected] ~]# echo 123 >/opt/1.txt
[Email protected] ~]# Cat/opt/1.txt

[Email protected] ~]# cat/opt/1.txt/etc/

[Email protected] ~]# cat/opt/1.txt/etc/>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt

[Email protected] ~]# cat/opt/1.txt/etc/2>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt

[Email protected] ~]# cat/opt/1.txt/etc/&>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt

###################################################################

/dev/null: Black hole equipment

Case 2: Create a user settings password

[Email protected] ~]# vim/root/user.sh
#!/bin/bash
Useradd nsd04 &>/dev/null
Echo User Nsd04 created successfully
Echo 123 | passwd--stdin nsd04 &>/dev/null
echo User nsd04 Password Setup succeeded

[Email protected] ~]# chmod +x/root/user.sh

[Email protected] ~]#/root/user.sh

Allow scripts to adapt to changing environments

Variable: The container holds the value that can change with the invariant name

[Email protected] ~]# vim/root/user.sh
#!/bin/bash
User=natasha
Useradd $user &>/dev/null
Echo User $user created successfully
Echo 123 | passwd--stdin $user &>/dev/null
echo User $user Password Setup succeeded

[Email protected] ~]#/root/user.sh

Assign a value to a variable:

   变量名=值read  为变量赋值,读入用户在键盘上的输入,将用户在键盘上的输入赋值给变量

[Email protected] ~]# cat/root/user.sh
#!/bin/bash
Read-p ' Please enter the user you want to create: ' Users
Useradd $user &>/dev/null
Echo User $user created successfully
Echo 123 | passwd--stdin $user &>/dev/null
echo User $user Password Setup succeeded

[Email protected] ~]#

[Email protected] ~]# cat/root/user.sh
#!/bin/bash
Read-p ' Please enter the user you want to create: ' Users
Read-p ' Please enter the password you want to set: ' Pass
Useradd $user &>/dev/null
Echo User $user created successfully
echo $pass | passwd--stdin $user &>/dev/null
echo User $user Password Setup succeeded

###############################################################
? Values that are stored as immutable names that may vary
– Variable name = variable Value
– Easy to reuse a value with a fixed name
– Improved adaptability to mission requirements and operational environment changes

Variable name
– Don't have spaces on both sides of the equals sign
– Variable names are made up of letters/numbers/underscores, case-sensitive
– Variable names cannot start with a number, do not use keywords and special characters

The name of the shell variable that is valid in the following variable name is (C)
A:-2-time b:_2$3 c:trust_no_1 D:2004file

View/reference variables
? Basic format
– Reference variable Value: $ variable Name
– View variable values: Echo $ variable name, echo ${variable name}

[Email protected] ~]# echo $a
Rhel
[Email protected] ~]# echo $a 7

[Email protected] ~]# echo ${a}7
Rhel7

$[] : 代表运算

[[email protected] ~]# echo $[1+1]

[[email protected] ~]# echo $[2*3]

[[email protected] ~]# echo $[2-3]

[[email protected] ~]# echo $[10/2]

[Email protected] ~]# echo $[10%2] #取余数运算

[[email protected] ~]# echo $[10%3]

[Email protected] ~]# a=7
[Email protected] ~]# b=3

[Email protected] ~]# echo $[$a + $b]

$(  )与` `: 将命令输出结果,作为参数

[Email protected] opt]# date +%f

[Email protected] opt]# mkdirdate +%F
[[email protected] opt]# ls

[Email protected] opt]# mkdir mariadb-date +%F
[[email protected] opt]# ls

[Email protected] opt]# mkdir hostname -date +%F
[[email protected] opt]# ls

 单引号‘ ‘ :  可以取消特殊字符的意义

Generate a random number $RANDOM

Generates a random number from a random number range of 0~99 $[$RANDOM%100]

Generates a random number from a random number range of 0~9 $[$RANDOM%10]

Residual operation: The remainder must be less than the divisor

##############################################################

Environment variables, complete by the system definition, assignment

? Common environment variables
USER: The system identity of the current login

Positional variables
? Command-line arguments that are provided when the script is executed
– Represented as $n, N is ordinal
–$1, $ 、.. .. ${10}, ${11} 、.. ..

[Email protected]/]# vim/root/test02.sh

#!/bin/bash
Cat-n $ | Head-$2

[Email protected]/]#/ROOT/TEST02.SH/ETC/PASSWD 4

Pre-defined variables
? The execution information used to save the script

$#    已加载的位置变量的个数(计算使用位置变量的总数)$*    所有位置变量的值$?    程序退出后的状态值,0表示正常,其他值异常

[Email protected]/]# vim/root/test02.sh

#!/bin/bash
Cat-n $ | Head-$2
Echo $#
Echo $*

[Email protected]/]#/ROOT/TEST02.SH/ETC/PASSWD 2

#############################################################
Condition testing and selection

? Check file status
-E: Exists as true
-D: Exists and is true for the directory
-F: Exists and is true for files
-R: Exists and Read permission to object is True
-W: exists and has write permission for the object to be true
-X: Exists and has execute permission on the object to be true

[Email protected]/]# [-E/ETC]
[[email protected]/]# echo $?
0
[Email protected]/]# [-e/etc/haha]
[[email protected]/]# echo $?
1
[Email protected]/]# [-D/ETC/PASSWD]
[[email protected]/]# echo $?
1
[Email protected]/]# [-D/ETC]
[[email protected]/]# echo $?
0
[Email protected]/]# [-F/ETC/PASSWD]
[[email protected]/]# echo $?
0

? Compare integer size (with G have greater than two words, with E is equal to two words, with L are less than two words)
-GT: Greater Than
-ge: greater than or equal to
-eq: Equals
-ne: Not equal to
-LT: Less than
-le: Less than or equal to

[Email protected]/]# a=7
[Email protected]/]# b=3
[Email protected]/]# [$a-ne $b]
[[email protected]/]# echo $?
0
[Email protected]/]# [$a-eq $b]
[[email protected]/]# echo $?
1
[Email protected]/]# [$a-ge $b]
[[email protected]/]# echo $?
0
[Email protected]/]# [$a-le $b]
[[email protected]/]# echo $?
1

? string alignment
= =: String Consistency is True
! =: String inconsistency is true

[Email protected]/]# [$USER = = Root]
[[email protected]/]# echo $?
0
[Email protected]/]# [Redhat = = Root]
[[email protected]/]# echo $?
1
[[Email protected]/]# [Redhat! = root]
[[email protected]/]# echo $?
0

###############################################################

If dual branch processing

If [Conditional judgment];then
Command Sequence 01
Else
Command Sequence 02
Fi

Case:
The computer randomly generates a number between 0~9
The user enters a number between 0~9

如果 计算机随机产生的数字 与  用户输入的数字  相等         则输出  恭喜您猜对啦如果 计算机随机产生的数字 与  用户输入的数字  不相等         则输出  再见

[Email protected]/]# vim/root/num.sh
#!/bin/bash
num1=$[$RANDOM%10]
Read-p ' Please enter a number between [0-9]: ' num2
If [$num 1-eq $num 2];then
Echo, congratulations on your guess.
Else
Bye, Echo.
Fi

If multi-branch processing

If [Conditional judgment 1];then
Command Sequence 01
elif [Conditional Judgment 2];then
Command Sequence 02
elif [Conditional Judgment 3];then
Command Sequence 03
Else
Command sequence 04
Fi

Case:
Judging user input Score
If the score is greater than or equal to 90, the output is excellent
Good output if score is equal to 80
If the result is greater than or equal to 70, the output passes
If the result is greater than or equal to 60, the output still needs effort
The above conditions are not satisfied then output in the cattle of Chopin, also can not play out the sadness of elder brother

[Email protected]/]# cat/root/nsd.sh
#!/bin/bash
Read-p ' Please enter your score: ' NSD

if  [ $nsd -ge 90 ];then  echo 优秀elif [ $nsd -ge 80 ];then  echo 良好elif [ $nsd -ge 70 ];then  echo 及格elif [ $nsd -ge 60 ];then  echo 仍需努力else  echo 在牛的肖邦,也弹不出哥的悲伤fi

##############################################################

Case:
The computer randomly generates a number between 0~9
The user enters a number between 0~9

如果 计算机随机产生的数字 与  用户输入的数字  相等         则输出  恭喜您猜对啦如果 计算机随机产生的数字 与  用户输入的数字  不相等 如果猜大了 则输出大了如果猜小了 则输出小了   

[Email protected]/]# cat/root/num.sh
#!/bin/bash
num1=$[$RANDOM%10]

read  -p  ‘请输入[0-9]之间的数字:‘    num2if [ $num1 -eq $num2 ];then   echo 恭喜您猜对了    exit  #退出脚本elif [ $num2 -gt $num1  ];then   echo 您猜大了else   echo 您猜小了fi

For loop structure

For variable name in value list
Do
Command sequence
Done

For a in Zhangsan Lisi Wangwu DC
Do
Useradd $a
Done

Variable a participates in the loop, and the variable a value affects the result of the loop
[Email protected]/]# vim/root/for.sh
#!/bin/bash
For a in Nsd11 nsd12 nsd13 nsd15
Do
Useradd $a
Echo $a created successfully
Done

Variable A does not participate in the loop, and the variable a value does not affect the result of the loop
#!/bin/bash
For a in 1 2 3
Do

   echo  hello  worlddone

[Email protected]/]# cat/root/num.sh
#!/bin/bash
num1=$[$RANDOM%10]
For a in {1..10}
Do
Read-p ' Please enter a number between [0-9]: ' num2
If [$num 1-eq $num 2];then
Echo, congratulations on your guess.
Exit #exit退出整个脚本
elif [$num 2-gt $num 1];then
Echo, you guessed big.
Else
echo, you guessed small.
Fi
Done

Shell scripting basics, using variables, conditional testing and selection, and list-looping

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.