1.8 linux foundation (eight) -shell script basis

1.8 linux foundation (eight) -shell script basis

1.8.1, create a shell script

  • Use a text editor to create a text file vim
  • The first line shell declaration must include the sequence:! # (Magic number)
  • #!/bin/bash
  • Add comments, which begin with # (try not to use Chinese)

1.8.2 implementation of the script

  • bash script-name.sh
  • /path/to/script-name.sh or ./script-name.sh script requires execute permissions for the job
给脚本增加执行权限:
chmod +x script-name.sh
  • or source. script-name
    • Note: The script will be the value of the variable or function return value passed to the parent shell will execute the command to load script variables in the current shell, rather than generating a sub-shell to execute the script. a, b are executed to generate pace sub-shell.
[root@CentOS7 data]# cat source.sh
#!/bin/bash 
#
name=10000 
[root@CentOS7 data]# name=0 
[root@CentOS7 data]# echo $name
0
[root@CentOS7 data]# sh source.sh
[root@CentOS7 data]# echo $name 
0
[root@CentOS7 data]# . source.sh
[root@CentOS7 data]# echo $name
10000
[root@CentOS7 data]# cat source2.sh
echo $name
[root@CentOS7 data]# . source2.sh
10000 ##一个脚本调用另一个脚本的参数

1.8.3, the script specification

The beginning of the script code agreement

1, the first line of language usually used to call

2, program name, to avoid changing the file name can not find the right file

3, the version number

4, after the change of time

5. Author information

6, the role of the program, and precautions

7, finally, a brief description of each version of the update

#!/bin/bash
# ------------------------------------------
# Filename: hello.sh
# Revision: 1.1
# Date: 2018/08/01
# Author: zhu
# Email: [email protected]
# Website: www.xxx.com
# Description: This is the first script
# ------------------------------------------
# Copyright: 2018 zhu
# License: GPL
echo “hello world

Script Debugger 1.8.4

Bash -n syntax error detection script / path / to / some_script

Step through debugging bash -x / path / to / some_scrip

1.8.5 develop a good habit to write scripts

  • A one-time symbol pairs to break out, then backspace add content sign in to prevent the omission
  • [] Brackets, [[]] ends must have two spaces
  • Flow control statements, which finished one-time format, add content
  • Make the code readable by indenting
  • String Defines a conventional variable value of the variable number should be added, and can not have a space before and after the equal sign, references require strong, with '', if the reference is a command, the double quotation marks ""
  • linux symbols are symbols in English state

1.8.6 write your first script hello world

[root@CentOS7 ~]# vim test1.sh
[root@CentOS7 ~]# cat test1.sh
#!/bin/bash

# ------------------------------------------

# Filename: test1.sh

# Revision: 1.1

# Date: 2018/08/01

# Author: zhu

# Email: [email protected]

# Website: www.studylinux.net

# Description: This is the first script

# ------------------------------------------

# Copyright: 2018 zhu

# License: GPL

echo "hello world"

1.8.7 write a script to script /root/bin/systeminfo.sh, displays the current host system information

Including host name, IPv4 address, operating system version, kernel version, CPU type, memory size, hard drive size

[root@CentOS7 ~]# cat /root/bin/systeminfo.sh
#!/bin/bash 
echo "OS_version is  `cat /etc/centos-release| grep -o "[0-9]\+"|head -n1`"
echo "Kernel_version is `uname -r`"
echo "IPv4 is `ifconfig ens33|grep "cast"|tr -s ' ' |cut -d" " -f3`"
echo "CPU_type is `lscpu |grep "Model name"|tr -s " " |cut -d: -f2`"
echo "Memory Size is `cat /proc/meminfo |head -n1 |tr -d " "|cut -d: -f2`"
lsblk|grep "^sd"|tr -s " "|cut -d " "  -f1,4`"
echo "Hostname is $HOSTNAME"
echo "My name is "$USER""

1.8.8 Variables

  • Variable: named memory space
  • Data storage: ASCII

    • Characters: 110
    • Value: 110
  • Variable effect:
    • 1, data storage format
    • 2, involved in the operation
    • 3, the data range indicated
  • Variable type:
    • character
    • Value: integer, float
  • Strongly typed: variables before use, must be declared in advance, and even need to initialize
  • Weak Type: variable prior to use, without prior declaration, will be involved in calculating implicit type conversion automatically. The default character form, bash does not support floating-point type.

  • Variable naming rules:
    • 1, so that the program can not be reserved words: For example if, for
    • 2, can only use numbers, letters and underscores, and can not begin with a number
    • 3, see the name to know justice
    • 4, unified naming rules: hump nomenclature
  • The following is divided into force variable type variable range standards:

  • Local variables: Effective range for the current shell process; for other than the current shell shell process, including the current sub-shell process shell are invalid
  • Environment (global) variables: Effective range for the current shell process and its children
  • Local variables: Effective range is a snippet of the current shell process, usually function
  • Location variables: $ 1, $ 2, ... are represented, for a script to call its argument passed to the command line in the script code
  • Special variables: $ ?, $ 0, $ *, $ @ # $, $$
  • PID of the current process: $$
  • $ !: PID executing one instruction

1.8.8.1 Local Variables

  • Variable Assignment: name = 'value'
  • You can use the reference value:
    • (1) may be a direct string; name = "root"
    • (2) variable reference: name = "$ USER"
    • (3) command references: name = `COMMAND` name = $ (COMMAND)
  • Variable references: $ {name} $ name
    • "": Weak references, wherein the variable reference variable value is replaced
    • '': Strong reference, wherein the variable reference variable value is not replaced, while retaining the original string
  • All variables defined display: set
  • Delete variable: unset name

1.8.8.2 Environment Variables

  • Variable declarations, assignment:
    • export name=VALUE
    • declare -x name=VALUE
  • Variable references: $ name, $ {name}
  • Show all environment variables:
    • env
    • printenv
    • export
    • declare -x
  • Delete variable: unset name

1.8.8.3 Read-only variables

  • Read-only variables: only declared, but not modify, and delete
  • Read-only variable declaration:
    • readonly name
    • declare -r name
  • View read-only variable: readonly -p

    1.8.8.4 position variable

  • Position variable: call parameters passed to the script from the command line in the script code
  • $ 1, $ 2, ...: the corresponding first and second parameters,
  • shift [n] position transducer
  • $ 0: command itself
  • "$ *": All the parameters passed to the script, all the parameters into one string corresponds to "$ 1 $ 2 $ 3"
  • "$ @": All the parameters passed to the script, would retain any blank all embedded in each parameter, all the parameters as different independent string equivalent of "$ 1" "$ 2" "$ 3"
  • $ #: The number of passing parameters to the script
  • $ @: All parameters passed to the script
  • $ *: All parameters passed by reference to the script, and only $ * $ # will have a difference in time is wrapped up in double quotes.
  • set - clear all variables position

[root@CentOS7 ~]#  name=parent;{ echo "1:$name";name=son;echo "2:$name"; };echo "3:$name"
1:parent  ## 花扩号在当前shell中执行,前后有空格,不开启子shell
2:son
3:son
[root@CentOS7 ~]#  name=parent;(echo "1:$name";name=son;echo "2:$name");echo "3:$name"
1:parent  ## 小括号在执行时,会开启子进程,子进程能拿到父进程的变量,子进程内变量赋值、内部命令将会影响子进程的环境,()执行完成后,子进程结束,不保留变量赋值。
2:son
3:parent

1.8.9 $? Command execution status return value (exit status)

Process to use the exit status reports success or failure

  • 0 for success for failure 1-255
  • $? Command execution state of a variable to hold the return value
  • For example: ping -c1 -W1 hostdown &> / dev / null echo $?

1.8.10 exit status

  • bash custom exit status codes
  • exit [n]: Custom exit status codes
  • Note: In the event of the exit command script, the script will terminate immediately; terminate the exit command to exit the state depends on the latter figure Note: If you do not specify exit status to the script, the whole script exit status depends on the last script execution status code command

1.8.11 Arithmetic

  • The arithmetic bash: bash Digital will perform an implicit type conversion
  • Arithmetic operators: +, -, *, /,% modulus (remainder), ** (power)
  • Implement arithmetic operations:
  • (1) let var = arithmetic expression
  • (2) var = $ [arithmetic expression]
  • (3) var = $ ((arithmetic expression))
  • (4) each = $ (expr arg1 arg2 arg3 ...)
  • (5) declare -i var = value
  • (6) echo "arithmetic expression" | bc
  • Multiplication sign some scenes need to be escaped, such as *
  • bash has built-in random number generator: $ RANDOM (0-32767) echo $ [$ RANDOM% 50]: a random number between 0-49
  • Enhanced assignment: + =, - =, * =, / =,% =
  • let varOPERvalue
  • For example: let count + = 3 i.e. count = count + 3 from the self-assignment plus 3
  • Increment, decrement:
  • was readily + = 1
  • was easily ++
  • easily heat = 1
  • easy var--

1.8.12 logical operation

  • true, false
  • 1, 0
  • versus:
    • 1 = 1 and 1
    • 1 and 0 = 0
    • 1 = 0 and 0
    • 0 and 0 = 0
  • or:
    • 1 1 = 1 or
    • 1 = 0 or 1
    • 1 = 0 or 1
    • 0 = 0 or 0
  • non:
    • ! 1 = 0
    • ! 0 = 1
  • Short circuit calculation
  • Short-circuit and
    • The first is 0, the result must be 0
    • The first is 1, the second must be involved in computing
  • Short or
    • The first is 1, the result is necessarily 1
    • The first is 0, the second must be involved in computing
  • XOR: ^
    • XOR two values, 0 false same, different true 1

1.8.13 test conditions

  • Determine whether certain requirements are met, it needs to be implemented by the testing mechanism
  • Note: special test expressions required by the test command auxiliary complete the testing process
  • Assessment Boolean statement for use in a conditional execution
    • If that returns 0
    • If false, it returns 1

      1.8.14 test command

  • test EXPRESSION
  • [ EXPRESSION ]
  • [[ EXPRESSION ]]
  • Note: You must have a trailing whitespace EXPRESSION

The value of the test 1.8.15 bash

  • Numerical test:
    • Is larger than whether -gt
    • Are -ge greater than or equal
    • It is equal to -eq
    • -ne not equal
    • Whether -lt less than
    • Are -le Less than or equal

1.8.16 bash string test

  • String test:
    • It is equal to =
    • > Ascii code ascii code is greater than
    • <Is less than
    • ! = Not equal
    • = ~ String is left can be matched to the right of PATTERN
    • NOTE: This expression is generally used [[]] in; extended regular expressions, PATTERN right without quotes
    • -z "STRING" string is empty, empty is true, not false empty
    • -n "STRING" string is not empty, empty is not true, empty is false

    • Note: The string used for comparison of operands should use quotation marks

[root@CentOS7 ~]# var=abcdef;[[ "$var" = abc* ]] && echo 1 || echo 0
1 ## [[  = ]] 支持通配符
[root@CentOS7 ~]# var=abcdef;[[ "$var" = "abc*" ]] && echo 1 || echo 0
0  ## 引号引起来的都视为是字符串
[root@CentOS7 ~]# filename=a.conf;[[ "$filename" =~ \.conf ]] && echo 1 || echo 0
1 ## 正则表达式不加引号

1.8.17 Bash file tests

Existence test 1.8.17.1 file

  • -a FILE: same -e
  • -e FILE: file exists testing, there are true and false otherwise

1.8.17.2 Document Type Test

  • -b FILE: and if there is a block device file
  • -c FILE: whether a file exists and is a character device
  • -d FILE: whether the file exists and is a directory
  • -f FILE: whether exists and is a regular file
  • -h FILE or -L FILE: file exists and is a symbolic link
  • -p FILE: whether a file exists and is a named pipe
  • -S FILE: whether the file exists and is a socket

1.8.17.2 Bash test file permissions

  • -r FILE: if there is readable
  • -w FILE: if exists and is writable
  • -x FILE: whether exists and is executable

1.8.17.3 special permissions file test:

  • -u FILE: the existence of privileges and have suid
  • -g FILE: the existence of privileges and have sgid
  • -k FILE: the existence of privileges and have sticky

1.8.17.4 Bash test file attributes

  • File size test:
  • -s FILE: and if there is non-empty

Are 1.8.17.5 File Open:

  • -t fd: fd file descriptor has been started in a terminal
  • -N FILE: file since the last time it was read has not been altered
  • -O FILE: The current user is a valid file owner
  • -G FILE: The current user is a valid file is a group

1.8.17.6 Bash test file attributes

  • Binocular tests:
    • FILE1 -ef FILE2: FILE1 FILE2 of whether it is a hard link
    • FILE1 -nt FILE2: if FILE1 is newer than FILE2 (mtime) - FILE1 -ot FILE2: FILE1 is older than FILE2 whether

1.8.17.7 Bash combination of test conditions

  • The first way:
    • COMMAND1 && COMMAND2 and
    • COMMAND1 || COMMAND2 or
    • ! COMMAND non
    • 如:[[ -r FILE ]] && [[ -w FILE ]]
  • The second way:
    • EXPRESSION1 -a EXPRESSION2 and
    • EXPRESSION1 -o EXPRESSION2 or
    • ! EXPRESSION 非
    • You must use the test command
    • Example:
[root@CentOS7 ~]# [ -z "$HOSTNAME" -o $HOSTNAME == "CentOS7.5.zhu.com" ] && echo 1 || echo 0
1
[root@CentOS7 ~]#[ -f /bin/cat -a -x /bin/cat ] && cat /etc/fstab
[root@CentOS7 ~]#[ -f /bin/cat -a -x /bin/cat ] && cat /etc/fstab
# /etc/fstab
# Created by anaconda on Wed Jul 18 17:26:27 2018

1.8.18 use the read command to accept input

  • Used to read the input values ​​assigned to one or more shell variable
    • -p prompt to be displayed,
    • -s silent input, generally used for password
    • N -n designation input character length N
    • -d 'character' end symbol
    • of N -t N TIMEOUT seconds
  • reads the value read from the standard input, all remaining words assigned to each word in a variable is assigned to the last variable
  • read -p "Enter a filename:" FILE

1.8.19 bash profile

  • By effective range is divided, there are two types:
  • Global Configuration: / etc / profile /etc/profile.d/*.sh / etc / bashrc
  • Personal configuration: ~ / .bash_profile ~ / .bashrc

1.8.20 shell are two ways to log on

  • Interactive logon:
  • (1) log in directly through the terminal enter the account password
  • User - "UserName su" switch (2)
  • The order of execution: / etc / profile -> /etc/profile.d/*.sh -> ~ / .bash_profile -> ~ / .bashrc -> / etc / bashrc
  • Non-interactive logon:
  • (1)su UserName
  • Open (2) graphical terminal
  • (3) execute the script
  • (4) any other instance of bash
  • The order of execution: ~ / .bashrc -> / etc / bashrc -> /etc/profile.d/*.sh

1.8.20.1 Profile category

  • profile categories: configured to provide interactive logon shell
    • Global: / etc / profile, /etc/profile.d/*.sh

    • Personal: ~ / .bash_profile

    • function:

    • (1) is used to define an environment variable

    • (2) run a command or script

1.8.20.2 Bashrc class

  • bashrc categories: interactive and non-interactive login shell provides configuration
    • Global: / etc / bashrc
    • Personal: ~ / .bashrc
    • function:
    • (1) and functions defined command aliases
    • (2) the definition of local variables

Edit the configuration file to take effect

  • After modifying the profile and bashrc file must take effect
  • Two ways:
    • 1 Restart the shell process
    • 2 or source
      Examples:. ~ / .Bashrc
  • Let arbitrary script has execute permissions a directory of input path can not be executed.
[root@CentOS7 scripts]# cat /etc/profile.d/zhu.sh
PATH=.:$PATH
[root@CentOS7 scripts]# . /etc/profile.d/zhu.sh
[root@CentOS7 scripts]# yesorno.sh
please input yes or no:y
Your answer is YES.
[root@CentOS7 scripts]# echo $PATH
.:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
tips:为了安全考虑,在生产中不建议这么做 

1.8.21 Bash Exit Task

  • Save ~ / .bash_logout file (user)
  • Running on exit login shell
  • For creating automatic backup
  • Clear temporary files

1.8.22 $ - variable

  • h: hashall, open this option, Shell will command the path where the hash of it and avoid every time the query. By The set + h h option off
  • i: interactive-comments, include this option to indicate the current shell is an interactive shell. The so-called interactive shell, in the script, i option is turned off (cat /etc/profile.d/vte.sh)
  • m: monitor, turn on monitor mode, you can control the process by Job control stop, continue, such as the background or the foreground.
  • B: braceexpand, brace expansion
  • H: history, H option is turned on, you can expand the list of the command history, can be accomplished by an exclamation point, for example, "!!" return on recent history command, "n!" To return to the n-th command history!

Guess you like

Origin www.cnblogs.com/huangsefeizhu/p/11505993.html
Recommended