Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Linux Bash programming syntax?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you what the Linux Bash programming syntax is. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

In the process of Linux learning, we will inevitably encounter a magical thing that is not only a favorite, but also a headache-bash programming, that is, shell script. So what is a shell script? Shell is a command language interpreter, while shell scripts are collections of Linux commands that are interpreted and executed in a preset order to complete specific and complex system administration tasks, similar to batch files in Windows.

Variables for bash programming

Bash variable category

Local variable: a variable that is only valid for the current shell process, but not valid for other shell processes, including the child processes of the current shell process

VAR_NAME=VALUE

Variable assignment: save data to the storage space of the variable

Variable reference: ${VAR_NAME}

"": weak reference, in which the variables will be replaced by'': strong reference, in which all characters are literal and output directly

Environment variable: valid for the current shell process and its child shell, invalid for other shell processes

Definition: export VAR_NAME=VALUE export: export VAR_NAME undo variable: unset VAR_NAME read-only variable: readonly VAR_NAME

Local variables: valid for a code snippet in a shell script, usually used locally in a function

Local VAR_NAME=VALUE

Position variable: a parameter used to accept the location specified by the variable

$1, 1, 7, 2, 7, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6

Special variables: shell does special treatment for some parameters, which can only be referenced and not assigned.

$# number of parameters passed to the script $* displays all parameters passed to the script # unlike the location variable, this option parameter can exceed 9 $$to get the process number of the current shell $! The process number for executing the previous instruction is $? Get the return value of the last instruction executed # 0: successful, non-zero: failed $- displays the current option used by shell, which has the same function as the set command $@ and $*, but uses it in quotation marks and returns each parameter in quotation marks

View variables:

Set: view all variables in the current shell process export, printenv, env: view all environment variables in the current shell process

Variable naming:

1. You cannot use keywords in the program (reserved words)

2. Only numbers, letters and underscores can be used, and cannot start with a number

3. To see the name and know the meaning

Variable type:

Numerical type: exact numerical value (integer), approximate numerical value (floating point) character type: char,string Boolean type: true, false

Type conversion:

Explicit conversion implicit conversion

Configuration file for bash:

Function: set local variables and define command aliases

Profile class: provides configuration for interactively logged-in users

Global: / etc/profile, / etc/profile.d/*.sh user: ~ / .bash_profile

Bashrc class: provides configuration for non-interactive users

Global: / etc/bashrc user: ~ / .bashrc

The programming format and execution mode of bash programming

Writing format: the first line of the shell script must be written at the top, and the script is interpreted with the specified interpreter defined by the shebang definition.

#! / bin/bash #! That is, shebang # other lines starting with # are comments that will be ignored by the interpreter and can be used to comment on the purpose and version of the script for ease of use and management.

Execution method: bash programming belongs to process-oriented programming, and the execution mode is as follows:

Sequential execution: select execution according to the sequence of commands: test conditions, there may be multiple test conditions, and when certain conditions are met, execute the corresponding branch loop execution: execute the same piece of code repeatedly, therefore, the loop must have exit conditions; otherwise, it will fall into a dead loop.

Bash execution options:

Bash-n SHELLNAME # syntax test, test for syntax errors bash-x SHELLNAME # simulates single-step execution, showing each step

Arithmetic Operation and logical Operation of bash

Arithmetic operation

Define integer variables: l

Et VAR_NAME=INTEGER_VALUE # for example: let axiom 3 declare-I VAR_NAME=INTEGER_VALUE # declare-I axiom 3

The way in which arithmetic operations are performed:

Let VAR_NAME=ARITHMATIC_EXPRESSION VAR_NAME=$ [ARITHMATIC _ EXRESSION] VAR_NAME=$ ((EXPRESSION)) VAR_NAME=$ (expr $num1 + $num2)

Arithmetic operator:

+: addition -: subtraction *: multiplication /: divisible%: take the remainder * *: power

Note: even if it is not defined as an integer variable, character numbers can still participate in arithmetic operations, and bash performs implicit type conversions for variable types.

Logical operation

Boolean operation: true, false and Operation: true & & True = True & & false = false & & True = false & & false = false or Operation: true | | True = True | | false = True / false | | false = false not operational:! True = false! False = true

Conditional test statements for bash programming

Bash conditional test

Integer testing: integer comparison

For example, [$num1-gt $num2]-gt: true if greater than-lt: true if less than-ge: true if greater than or equal to-le: true if less than or equal to-eq: true if equal to-ne: true if not equal to

Character tests: string comparison

Binocular: for example, [["$str1" > "$str2"] >: true if greater than or equal to true / dev/null;then useradd $1 fi 2, double branch statement structure of if statement: if test condition Then Select Branch 1 else Select Branch 2 fi execute only one of the two branches: give a file path through the command line, and then determine: if there are blank lines in this file, display the total number of blank lines Otherwise, no blank lines are displayed; #! / bin/bash if grep "^ [[: space]] * $" $1 & > / dev/null; then echo "$1 has $(grep" ^ [[: space]] * $"$1 | wc-l) blank lines." Else echo "No blank lines" fi Note: if you treat the success of the command execution as a condition, the if statement must be followed only by the command itself, not referenced. 3. The multi-branch sentence structure of if sentence: if condition 1 then branch 1 elif condition 2 branch 2 elif condition 3 branch 3. Else branch n fi example: pass a user name to the script: if the user's id number is 0, it is said to be an administrator; if the user's id number is greater than or equal to 500, it is said to be an ordinary user; otherwise, it is said to be a system user. #! / bin/bash if [$#-lt 1]; then echo "Usage: `basename $0` username" exit 1 fi if! Id-u $1 & > / dev/null; then echo "Usage: `basename $0` username" echo "No this user $1." Exit 2 fi if [$(id-u $1)-eq 0]; then echo "Admin" elif [$(id-u $1)-ge 500]; then echo "Common user." Else echo "System user." Fi

Bash interactive programming

Read [option] "prompt"-p: directly specify a variable to accept the parameter-t timaout: specify the time to wait for the parameter to be accepted-n: do not wrap the line example: enter a user name and return its shell #! / bin/bash read-p "Plz input a username:" userName if id $userName & > / dev/null; then echo "The shell of $userName is `grep" ^ $userName\ > "/ etc/passwd | cut-d:-f7`." Else echo "No such user. Stupid." Fi

Case statement for conditional testing

Case statement: when there are multiple test conditions, the case statement will make the syntax structure clearer: case variable references in PATTERN1) branch 1;; PATTERN2) branch 2;;. *) branch n;; esac

PATTERN: similar to the file name wildcard mechanism, but supports the use of | indicates or

A | b: an or baked: match any character of any length?: match any single character in the specified range []: write a script to complete the following tasks: script.sh {start | stop | restart | status} where: if the parameter is empty, help information is displayed and exit the script If the parameter is start, an empty file / var/lock/subsys/script is created and "starting script successfully." If the parameter is stop, delete the file / var/lock/subsys/script and display "Stop script successfully." If the parameter is restart, delete the file / var/locksubsys/script and recreate it, followed by the display of "Restarting script successfully." If the parameter is status, then: if the file / var/lock/subsys/script exists, "Script is running …" is displayed. Otherwise, it displays "Script is stopped." #! / bin/bash file='/var/lock/subsys/script' case $1 in start) if [- f $file]; then echo "Script is running..." Exit 3 else touch $file [$?-eq 0] & & echo "Starting script successfully." Fi;; stop) if [- f $file]; then rm-rf $file [$?-eq 0] & & echo "Stop script successfully." Else echo "Script is stopped..." Exit 4 fi; restart) if [- f $file]; then rm-rf $file [$?-eq 0] & & echo "Stop script successfully" else echo "Script is stopped..." Exit 5 fi touch $file [$?-eq 0] & & echo "Starting script successfully";; status) if [- f $file]; then echo "Script is running..." Else echo "Script is stopped." Fi;; *) echo "`basename $0` {start | stop | restart | status}" exit 2;; esac

Circular statement of bash programming

For cycle of cycle

1. For statement format: sentence structure: for variable name in list; do loop body done list: can contain one or more element loop body: rely on calling variables to achieve its change loop nesting exit condition: traversing element list ending example: find the sum of all positive integers up to #! / bin/bash declare-I sum=0 for i in {1... 100} Do let sum+=$i done echo $sum 2, for statement format 2 for ((initial condition; test condition; modify expression); do loop body done first uses the initial condition and test condition to judge, if it meets the test condition, executes the loop body, and then modifies the expression, otherwise it directly jumps out of the loop. Example: find the sum of all positive integers within 100 (for 2 implementation) #! / bin/bash declare-I sum=0 for ((counter=1;$counter / dev/null; then grep "^ $userName\ >" / etc/passwd | cut-d:-f3 else echo 7 else echo "No such user." Fi read-p "Plz enter a username again:" userName done while Special usage: traversing text file statement structure: while read variable name; do loop body done

< /path/to/somefile 变量名,每循环一次,记忆了文件中一行文本 例:显示ID号为偶数,且ID号同GID的用户的用户名、ID和SHELL while read line; do userID=`echo $line | cut -d: -f3` groupID=`echo $line | cut -d: -f4` if [ $[$userID%2] -eq 0 -a $userID -eq $groupID ]; then echo $line | cut -d: -f1,3,7 fi done < /etc/passwd 循环之until语句 语句结构: until 测试条件; do 循环体 done 测试条件为假,进入循环;测试条件为真,退出循环 例:求100以内所有偶数之和,要求使用取模方法(until实现) #!/bin/bash declare -i counter=1 declare -i sum=0 until [ $counter -gt 100 ]; do if [ $[$counter%2] -eq 0 ]; then let sum+=$counter fi let counter++ done echo $sum 例:提示用户输入一个用户名,如果用户存在,就显示用户的ID号和shell;否则显示用户不存在;显示完成之后不退出,再次重复前面的操作,直到用户输入q或quit为止(until实现) #!/bin/bash read -p "Plz enter a username: " userName until [ "$userName" = 'q' -a "$userName" = 'quit' ]; do if id $userName &>

/ dev/null; then grep "^ $userName\ >" / etc/passwd | cut-d:-f3 7 else echo "No such user." Fi read-p "Plz enter a username again:" userName done

Cycle Control and shift of cycle

Loop control command: break: exit the loop break [N]: exit the N-tier loop; when N is omitted, it means to exit the loop where the break statement is located continue: end the current cycle ahead of time and directly enter the next cycle continue [N]: the current cycle of the N-tier cycle ahead of time, and directly into the next cycle.

Endless cycle:

# whilebody while true; do loop body done # until false; do body done example 1: write a script to determine whether a given user is logged in to the current system (1) if so, the script terminates; (2) every 5 seconds, check whether the user is logged in #! / bin/bash while true; do who | grep "gentoo" & > / dev/null if [$?-eq 0]; then break fi sleep 5 done echo "gentoo is logged."

Shift:

If there are no numbers, only shift skips one parameter to get the next parameter, and if you add a number, such as shift 2, skip two parameters to get the next parameter. For example, write a script in the form of showifinfo.sh [- I INTERFACE |-a] [- v] as follows: 1,-I or-a cannot be used at the same time,-I is used to specify a specific Nic interface, and-an is used to specify all interfaces; to display the ip address 2 of the interface and to use-v indicates that the details are displayed, showing the ip address, subnet mask and broadcast address of the interface 3. By default, only the-an option is used; #! / bin/bash allinterface=0 ifflag=0 verbose=0 interface=0 if [$#-eq 0]; then ifconfig | grep "inet addr:" | awk'{print $2}'fi while [$#-ge 1]; do case $1 in-a) allinterface=1 shift 1;;-I) ifflag=1 interface=$2 shift 2;;-v) verbose=1 shift 1;; *) echo "error option" exit 2 Esac done if [$allinterface-eq 1]; then if [$ifflag-eq 1]; then echo "command not found" exit 5 fi if [$verbose-eq 1]; then ifconfig | grep "inet addr:" else ifconfig | grep "inet addr:" | awk'{print $2}'fi fi if [$ifflag-eq 1]; then if [$allinterface-eq 1]; then echo "command not found" exit 5 fi if [$verbose-eq 1] Then ifconfig $interface | grep "inet addr:" else ifconfig $interface | grep "inet addr:" | awk'{print $2}'fi fi

Functions of bash programming

Grammatical structure:

Function F_NAME {function body} F_NAME () {function body}

Callable: use the function name, where the function name appears, will be automatically replaced with the function

The return value of the function:

The return value of the execution result of the function: the output of the code

Print statements are used in the function: echo, printf

The result returned after the execution of the system command called in the function

Execution status return value:

The default depends on the result of the last command executed by the function body.

Custom exit status code: return [0255]

Note: when the function body is running, the function returns as soon as it encounters the declare statement.

The function can accept parameters:

Function parameters are called in the same way as script parameters are called in the function body:

Location parameter $1, $2, … $, $*, $@

Example: write a script to perform the following functions (using functions):

1. Prompt the user for an executable command

2. Get all the library files on which this command depends (using the ldd command)

3. Copy the command to the directory corresponding to / mnt/sysroot/

Explanation: suppose that if you are copying a cat command and the path of its executable is / bin/cat, then you should copy / bin/cat to the / mnt/sysroot/bin/ directory. If you copy the useradd command and the executable path of useradd is / usr/sbin/useradd, copy it to the / mnt/sysroot/usr/sbin/ directory.

4. Copy the library files to the corresponding directory of / mnt/sysroot/

#! / bin/bash target=/mnt/sysroot/ [- d $target] | | mkdir $target preCommand () {if which $1 & > / dev/null; then commandPath= `which-- skip-alias $1`return 0 else echo "No such command." Return 1 fi} commandCopy () {commandDir= `dirname $1` [- d ${target} ${commandDir}] | | mkdir-p ${target} ${commandDir} [- f ${target} ${commandPath}] | | cp $1 ${target} ${commandDir}} libCopy () {for lib in `dirname $1 | egrep-o "/ [^ [: space:]] +" ` Do libDir= `dirname $lib` [- d ${target} ${libDir}] | | mkdir-p ${target} ${libDir} [- f ${target} ${lib}] | | cp $lib ${target} ${libDir} done} read-p "Plz enter a command:" command until ["$command" = = 'quit']; do if preCommand $command & > / dev/null; then commandCopy $commandPath libCopy $commandPath fi read-p "Plz enter a command:" command done

Signal capture in bash programming

The trap command is used to capture a signal in a shell program, after which you can react in three ways:

(1) execute a program to process the signal

(2) default operation of accepting signals

(3) ignore this signal

Trap provides three basic forms for the above three ways:

The first form of trap command executes the command string in double quotes when shell receives a signal with the same value in the signal list list.

Trap 'commands' signal-list trap "commands" signal-list

The second form of trap command restores the default operation of the signal:

Trap signal-list

The third form of trap command allows you to ignore the signal:

Trap "" signal-list trap 'COMMAND' SIGINT (meaning to shut down the process)

Example: write a script that can ping to detect whether all hosts in the specified network are online, and can receive ctrl+c commands to exit when the execution is not finished.

#! / bin/bash quitScript () {echo "Quit..."} trap 'quitScript; exit 5' SIGINT cnetPing () {for i in {1... 254}; do if ping-c 1-W 1 $1.Secreti & > / dev/null; then echo "$1.Secreti is up." Else echo "$1.Secreti is down." Fi done} bnetPing () {for j in {0.255}; do cnetPing $1.qij done} anetPing () {for m in {0.255}; do bnetPing $1.millim done} netType= `echo $1 | cut-d "."-f1`if [$netType-ge 1-a $netType-le 126]; then anetPing $netType elif [$netType-ge 128-a $netType-le 191] Then bnetPing $(echo $1 | cut-dudes.'- F1 le 2) elif [$netType-ge 192-a $netType-le 223]; then cnetPing $(echo $1 | cut-dudes.'- F1-3) else echo "Wrong" exit 2 fi

Array of bash programming

Array: multiple consecutive independent memory spaces, each equivalent to a variable

Array elements: array name + index (numbered from 0)

Representation of the index: a [0], a [1]

Declare an array:

Declare-an ARRAR_NAME

Associative array:

Declare-An ARRAY_NAME

Support for sparse formats: only one-dimensional arrays

Assignment of array elements:

(1) assign only one element at a time

A [0] = $RANDOM

(2) assign all elements at once

A = (red blue yellow green)

(3) specify an index for assignment

A = ([0] = green [3] = red [2] = blue [6] = yellow)

(4) user input

Read-an ARRAY

Array access:

Access with index:

ARRAY [index]

Length of the array:

${# ARRAY [*]} ${# ARRAY [@]}

Example: write a script, generate 10 random numbers, save them to the array, and then display the elements marked as even in the array

#! / bin/bash for i in {0.9}; do rand [$I] = $RANDOM [$[$I% 2]-eq 0] & & echo "$iRANDOM ${rand [$I]}" done

To select an element from an array:

${ARRAY [@]: offset:number}

Slice:

Offset: number of elements offset number: number of elements taken out ${ARRAY [@]: offset}: all elements after the offset is taken out ${ARRAY [@]}: all elements are taken out

Array replication: to use ${ARRAY [@]}

$@: each parameter is a separate string $*: all parameters are a string

Append elements to the array: non-sparse format

Week, week [${# week [@]}]

Remove elements from the array:

Unset ARRAY [index]

Example: copy the elements in an array with an even subscript to a new array

#! / bin/bash declare-a mylogs logs= (/ var/log/*.log) echo ${logs [@]} for i in `seq 0 ${# logs [@]} `; do if [$[$I% 2]-eq 0]; then index=$ {# mylogs [@]} mylogs [$index] = ${logs [$I]} fi done echo ${mylogs [@]}

Example 2: generate 10 random numbers and sort them in ascending order

#! / bin/bash for ((ibombac-1)) do for ((jumb0-witj)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report