Three. Shell scripts

Source: Internet
Author: User
Tags case statement stdin

##### #shell Script ##########
Bash Script Basics
BASH = GNU Bourne-again Shell,bash is a project developed and promoted by the GNU organization.
Bash scripts are similar to batching, simply by putting a lot of instructions together and providing loops,
conditions, judgments and other important functions, the syntax is simple and practical to write programs, greatly simplifying the administrator's
Functions that cannot be achieved by the graphical tools.

How do I create a new shell script?
1. Create a text file that contains the bash command. The first line of the file should be:
#!/bin/bash
2. Make the file executable (using chmod +x scripts)
3. Place the file in the user's $path directory
~/bin– Private programs for users
/usr/local/bin– Local development, scripts used by others on the system
/usr/local/sbin-locally developed, root-used scripts
Running scripts directly and running scripts with the source command is different!
Script Debug Mode:
#!/bin/bash-x
# Bash-x Scripts


Weak references
Place the string in double quotes, preserving the literal value of all characters in the string, except for the $, ', \, and! characters. In other words, the variable
Extensions and command extensions still work within double quotation marks.
echo "The current time is $ (date +%r)."
[Email protected] html]# echo "The current time is $ (date +%r)."
"The current time is 06:53 A.M. 23 seconds."

Strong references
Place the string in single quotation marks, preserving the literal value of all characters in the string, and disabling all extensions:
echo "Make $$$ Fast"
[[email protected] html]# echo "Make $$$ Fast"
"Make 1151$ Fast"

Escape
The non-referenced \ is an escape character. It retains the literal value of the next character. (for example, \ $PATH is the exact string $path, and
is not the contents of the PATH variable. )
[Email protected] ~]# echo "$HOME"
/root
[Email protected] ~]# echo "' pwd '"
/root
[Email protected] ~]# echo "" Hello, World ""
Hello, World
[[email protected] ~]# echo "\ $HOME"
$HOME
[[email protected] ~]# echo "\ ' pwd\ '"
' PWD '
[Email protected] ~]# echo "\" Hello, world\ ""
"Hello, World"

Shell calculation Commands:
Use $[] to represent mathematical operations. Use let to indicate mathematical operations. Use expr to represent mathematical operations.
Use (()) to indicate a mathematical operation. Bash built-in features, high efficiency.
[[email protected] html]# let a=1+2
[Email protected] html]# echo $A
3

Loops and calculations: # #for do-Done loops
#!/bin/bash
For ((i=1;i<=100;i++))
Do
((j+=i))
#j = ' expr $j + $i '
#let j+=i
#j =$[j+=i]
Done
Echo $j

Cases:
For ((i=1;i<=10;i++)); Do echo $i;d one
1
2
3
4
5
6
7
8
9
10


Database backup

Echo-n # #表示不换行
-E # #执行
\ r r\ # #覆盖上次结果

Bash-x Script # #测试脚本
&& conditions established
|| Conditions are not tenable

Countdown 1min10s
#!/bin/bash
Min=1
for ((sec=10; sec>=0; sec--))
Do
Echo-ne "After ${min}:${sec}s is end"
Sleep 1
Echo-ne "\ r \ r"
While ["$SEC"-le "0"-a "$MIN"-GT "0"]
Do
Echo-ne "After ${min}:${sec}s is end"
Echo-ne "\ r \ r"
((min--))
sec=10
Done
Done

Countdown 1min10s
for ((sec=70; sec>=0; sec--))
Do
Echo-ne "After $ (($SEC/60)): $ (($SEC%60)) s is End"
Echo-ne "\ r \ r"
Sleep
Done


Database-ne Progressive Display
Mysql-uroot-predhat-e "show databases;"-ne | Grep-e "^\*|schema$"-V # #显示出数据库

Script:
#! /bin/bash
For x in $ (mysql-uroot-predhat-e "show databases;") -ne | Grep-e "^/*|schema$"-V)
Do
Mysqldump-uroot-predhat $x >/mnt/&x-' Date '. Dump
Done



["0" = "0"]
echo $?
0

["0" = "0"]
echo $?
1

Position parameters themselves: $, $, $, $ ....
All positional parameters: [email protected], $*


1 #!/bin/bash
2 echo "$"
3 echo "$"
4 echo "$"
5 echo "$*"
6 echo "[Email protected]"
Ailwestos mnt]# sh test Red Hat Linux
Red
Hat
Linux
Red Hat Linux
Red Hat Linux



[-Z "$a"] && echo yes | | Echo No
# #当脚本后面没有跟变量时, Output Yes
[-N "$a"] && echo yes | | Echo No
# #当脚本后面有变量时, Output Yes

#!/bin/bash
Read-p "Please input your users:" username
Useradd $username
Read-p "Please input your password:" passwd
echo ' $passwd ' | passwd--stdin $username

Binary file Operators
-ef See if the hard-link node numbers are consistent # #ln软连接
-NF Viewing time stamps
-ot than what old


Determine if the number entered is less than 10
#!/bin/bash
Read-p "Please input a number:" A
["$a"-le 10-a "$a"-ge 0] && echo yes | | Echo No


If statement
The IF command checks the exit value of the command or list after if. If the first command evaluates to true/0, then run then
List of commands to be followed until any else. If the first command evaluates to false/nonzero, run the Else and fi
A list of commands between (anti-ping write if, mark the end of the If block).
Syntax: if command; then command; Command2; else Command3; Fi
Example:
if test "$USER"! = ' root '; Then
echo logged in as root
Fi
If [$ (id-u)-LT 9]; Then
echo "The number $ (id-u) is less than 9!"
Fi
If grep "^${user}:"/etc/passwd &>/dev/null; Then
echo "${user} is a local USER on the system."
Else
echo "${user} is not a local USER."
Fi

Case statement
Case statement: It is able to match the contents of a variable with multiple templates, and then decide what to do according to the template that successfully matches
Part of the code.
Case "$" in
Start
Systemctl Start $
;;
Stop
Systemctl Stop $
;;
Reload|restart)
Systemctl Stop $
Systemctl Start $
;;
*)
echo "Usage: $ start|stop|restart|reload"
;;
Esac



Determine what the file is
#!/bin/bash
Read-p "Please input a filename:" File
If
[-E $file]
Then
echo "File is existed"
Else
echo "File is not existed"
Fi
If
[-B $file]
Then
echo "Block Device"
Elif
[-C $file]
Then
echo "Character device"
Elif
[-F $file]
Then
echo "Normal file"
Elif
[-D $file]
Then
echo "Catalog"
Elif
[-L $file]
Then
echo "Connection File"
Else
echo "File is not existed"
Fi


Create a user's script
#! /bin/bash
max=$ (Wc-l $ | cut-d ""-F 1)

For NUM in $ (seq $MAX)
Do
username=$ (sed-n ${num}p $)
passwd=$ (Sed-n ${num}p)
Useradd $USERNAME
echo $PASSWD | passwd--stdin $USERNAME
Done

Getent passwd User1 # # Show user Information

Vim/etc/profile
Export A=5 Environment variables

Expect statements
Implementing an auto-answer script in the shell with expect
Yum Install Expect-y
Expect # #自动应答

Vim Answer.exp
chmod +x Answer.exp
/mnt/answer.exp
#!/usr/bin/expect
spawn/mnt/ask.sh
Expect "Name:"
Send "lee\r"
Expect "old"
Send "18\r"
Expect "class"
Send "linux\r"
Expect "Happy"
Send "happy\r"
Expect EOF


# #ssh连接

#!/usr/bin/expect
Set ipaddr [lindex $argv 0]
Set PASS [lindex $argv 1]

Spawn ssh [email protected] $IPADDR
Expect {
"Yes/no"
{send "yes\r"; Exp_continue}
"Password:"
{send "$PASS \ r"}
}
Interact
~

#!/bin/bash
For NUM in {1..10}
Do
Ping-c1-w1 172.25.254. $NUM &>/dev/null && (
/mnt/ssh.exp 172.25.254. $NUM redhat hostname | Grep-e "^the| Ecdsa|connecting| Warning|password|spawn "-v|sed" s/permission\ denied\,\ please\ try\ again\./172.25.254. $NUM password is error/g "
)
Done

This article from "12100661" blog, declined reprint!

Three. Shell scripts

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.