"Bash Scripts"

Source: Internet
Author: User
Tags case statement

I. Shell script Basics
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.

1. Create a text file that contains the bash command. The first line of the file should be:
#!/bin/bash
#!/usr/bin/env tcsh "Write this without looking for the specified bash directory, automatic search in env execution"

2. Make the file executable (using chmod +x scripts;sh ~.sh)

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

Two. Basic commands
1. References (high strength to the end)
‘ ‘
" "
2. Escaping
\
3. Execution of commands
` `
4. Variables
Name=hxl
Echo $name

5. Command replacement
Time= ' Dade '
Weather=is Sun
Echo $Time $weather

6. Arithmetic operator (similar to C language)
< variable >++
< variable >--
-
+
**
*
/
%
+=
-+

7. Calculation commands
Echo $[1+2]
Echo ' expr 1 + 2 ' (Plus and counting must be empty, otherwise it would be a whole)
Let A=1+2 Echo $A
Use (()) to indicate a mathematical operation. Bash built-in features, high efficiency. (used in scripts)



Test-{b|c|e|f|d|r|w|x|s| L} file/directory

[-b/dev/sda];echo $?] "Determine if the file is a block device"
1
[-c/dev/sda];echo $?] "Determine if the file exists and is a character device"
0
[-e/dev/sda];echo $?] "Determine if a file exists, commonly used"
0
[-f/dev/sda];echo $?] "To determine if a file exists and is a file, commonly used"
0
[-d/dev/sda];echo $?] "To determine if a file exists and is a directory, commonly used"
1
[-l/dev/sda];echo $?] "Determine if the file exists and is a linked file"
1

Test-{ZN} string

Test-z string "to determine if the string is 0? True if string is an empty string"
Test-n string "Judging if the string is not 0?" False if String is an empty string

Two. The binary file operator:-ef,-nt,-ot

[/bin/mount-ef/usr/bin/mount];echo $?] "Determine if two files are the same file and can be used to determine the hard link. The main significance is to determine whether two files point to the same Inode "
0
[/bin/mount-nt/usr/bin/mount];echo $?] "Judging whether/bin/mount is newer than/usr/bin/mount"
1
[/bin/mount-ot/usr/bin/mount];echo $?] "Judging whether/bin/mount is older than/usr/bin/mount"
1

Logical operators:-o,-a,!, &&,| |

[2-gt 1-a 1-gt 2];echo $? (2>1and 1>2, error)
1
[2-gt 1-o 1-gt 2];echo $? (2>1 or1>2, correct)
0
[!2-gt 1];echo $?] (Non-2>1, error)
1

Three. "Statement"
For statement
For HOST in hxl{1..3};d o echo $HOST;d one
HXL1
HXL2
HXL3

vim/etc/2.sh
#!/usr/bin/env tcsh
For ((i=1;i<=10;i++))
Do
((j+=i))
#j = ' expr $j + $i ' [All three methods available]
#let j+=i
#j =$[j+=i]
#declare-I. j+=i
Done
Echo $j

"Database backup Small Script"

Vim msqdump.sh

#!/bin/bash

For x in $ (mysql-uroot-phxl-e "show databases;") -ne | Grep-e "^\*|schema$"-V)
Do
MYSQLDUMP-UROOT-PHXL $x >/mnt/$x. Dump
Done
(-ne is for database table information to be sorted horizontally, not in tabular form)
If statement
Syntax: if Command;then command1;command2;elsecommand3;fi

Example
#!/usr/bin/env tcsh
If ["$USER"! = "root"];then "can only be used in! =, cannot use-nq", =,!=, ... Represents a character type, while-eq,-nq. Represents an integral type
echo "I ' m notroot"
Else
echo "I ' m root"
Fi

Case statement: It can match the contents of a variable with multiple templates and then decide which part of the code should be executed according to the template that successfully matches

#!/bin/bash
Case "$" in
Banana
echo Apple
;;
Apple
echo Banana
;;
*)
echo Shab
;;
Esac

"*expect" implements the auto-answer script

Vim/shell/talk

#!/bin/bash
echo "Who is you?"
Read who
echo "Hello, $who"
echo "Is You happy?"
Read answer
echo "Why?"
Read answer

Vim/shell/auto.exp

#!/usr/bin/expect
#set Timeout 3 "Setting the timeout for waiting response for all subsequent expect commands, in the unit is wonderful"
Spawn/shell/talk.sh "Spawn is the internal command of expect, the function is to add an access source to the SHELL command behind, pass the interactive instruction"
Expect "Who is You" "Determines if there is a matching field in the access source, returns immediately if any, or waits for the time-out to return"
Send "Hxl\n" "performs interactive action, equivalent to manually entering" HXL "
Expect "is you Happy"
Send "Yes,i am happy.\n"
Expect "why?"
Send "You ah me!\n"
Expect EOF "function is to search for the file terminator in the input, if there is no such line, the script will immediately exit, do not get the correct result"
Exit


Interact "After the completion of the implementation of the interactive State, the control to the console, this time it can be manually operated, otherwise exit login"

Four. $ARGV parameter array
Expect scripts can accept parameters that are passed from bash. can be obtained using [lindex $argv n], n starting from 0, respectively
One, the second, the third .... Parameters.

Example, execute SSH once [email protected][1..10] Redhathostname

vim/shell/hnmame.sh

num=160
Ping-c1-w1 172.25.254. $NUM &>/dev/null &&/bash/ssh.exp172.25.254. $NUM redhat hostname


Vim/shell/ssh.exp

#!/usr/bin/expect
Set IP [lindex $argv 0]
Set PASS [lindex $argv 1]
Set COMM [lindex $argv 2]
Spawn ssh [email protected] $IP $COMM
Expect {
"Yes/no"
{send "yes\r"; Exp_continue} [This is a choice to answer the format, if the retrieval of "yes/no", then answer yes, not retrieved to continue the following search]
"Password"
{send "$PASS \ r"}
}
Interact


5. Environment variables
To start a new bash in the current bash, it is generally necessary to re-assign values to variables that have already been defined. If you do not want to reassign the value, you need to add the original variable to the environment variable, because: The subroutine inherits only the environment variables of the process, and does not inherit the custom variables of the husband process.

For example
Name=hxl
Export name [add name to environment variable]
bash [start new bash]
Echo $name
HXL
Methods added to the environment variable: 1.export variable name; 2.declare-x variable name

declare [-AIXR] variable name

DECLARE-A variable name "Defines the variable as an array type"
Declare-i variable name "define variable as shaping (interger) type"
Declare-i num=1+2+3 [No Declare-i,echo $num or 1+2+3]
Echo $num
Declare-x variable Name
Declare-r variable name "Sets the variable to the readonly type, the variable cannot be changed, and cannot be reset"
Declare-p variable name "View variable is set to that attribute"
Declare-p num
Declare-i num= "6"

6. Setting aliases alias and Unalias

Example (a space must be added ")
Alias c= ' Clear ' specifies C as the clear command
"Note" If the command is the same, alias is preferred; If you don't want to change it every time, you can write a. bashrc file in the user's private directory



"Bash Scripts"

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.