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

The use of bash programming in Linux

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article will share with you how to use bash programming in Linux. This article introduces the variables of bash, the configuration file of bash and the syntax structure and function use of bash statements. I hope you can get something through this article.

I. variables of bash programming

1) bash variable category

Local variable: a variable that is valid only for the current shelll process, is not valid for other shell processes, and contains the children of the current shell process.

2) variable assignment:

That is, the data is saved to the storage space of the variable, as follows

[root@localhost ~] # VAR_NAME=VALUE3) variable reference

Format: ${VAR_NAME}

"": weak reference, where variables are replaced;'': strong reference, where all characters are literal, output directly, WYSIWYG; 4) environment variable

Valid for the current shell process and its child shell, but not for other shell processes!

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

Defined in shell scripts, can only be used in shell scripts!

6) location variable $1, special variable.

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 / / different from the location variable, this option parameter can exceed 9 $$: get the process number of the current shell $!: the process number of the last instruction executed $?: get the return value of the last instruction executed / / 0 means the execution is successful Non-zero is execution failure $-: 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 8) View variable set: view all variables in the current shell process Export, printenv, env: view all environment variables in the current shell process; 9) variable naming rules 1) do not use keywords in the program; 2) only use numbers, letters and underscores, not start with numbers; 3) system variables are capitalized by default, custom variables should not conflict with system variables; 4) try to see the meaning of the name 10) variable type 1) numeric type: exact value (integer), approximate value (floating point number); 2) character type: char, string;3) Boolean type: true, false;11) type conversion 1) display conversion; 2) implicit conversion; 2. Configuration file of bash

Function: set local variables and define command aliases.

1) profile class

Profile class: provides configuration for interactively logged-in users!

Global: / etc/profile, / etc/profile.d/*.sh user: ~ / .bash_profile2) bashrc class

Bashrc class: provides configuration for non-interactive users!

Global: / etc/bashrc user: ~ / .bashrc1) bash programming means writing format and execution mode 1) 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 shabang definition.

#! / bin/bash / /! That is, other lines starting with # in shebang// are comments, which will be ignored by the interpreter and can be used to comment on the purpose and version of the script, making it easy to use and manage. 2) execution mode

Bash programming is process-oriented programming, which is executed in the following ways:

1) Sequential execution: execute in sequence of commands; 2) Select execution: test condition, which may lead to multiple test conditions, and execute the corresponding branch when a condition is met; 3) Loop execution: the same piece of code is executed repeatedly many times, so the loop must have an exit condition; otherwise, it falls into a dead loop; 3) bash execution option 1) bash-n SHELLNAME # syntax test to test whether there is a syntax error 2) bash-x SHELLNAME # simulates single-step execution, showing each step of execution; 2) arithmetic operation and logic operation of bash 1) arithmetic operation

Define integer variables:

1) et VAR_NAME=INTEGER_VALUE / / for example: let axiom 32) declare-I VAR_NAME=INTEGER_VALUE / / for example: declare-I axi3

The way in which arithmetic operations are performed:

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

Algorithm operator:

+: addition -: subtraction *: multiplication /: divisible%: take 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.

2) logical operation Boolean operation: true, false and operation: true & & true = true & & false = false & & true = false & & false = false or operation: true | | true = true | | false = true or false | | true = true or false | | false = false not operation:! True = false! False = True 3) conditional Test statement for bash programming 1) bash conditional Test

Integer testing: integer comparison

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

Character tests: string comparison

Binocular: for example, [["$str1" > "$str2"] >: greater than or equal to true =: greater than or equal to true / dev/null;then useradd $1fi2, double branch statement structure of if statement: if test condition; then select branch 1else choose branch 2fi only one of the two branches to execute: 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/bashif grep "^ [[: space]] * $" $1 & > / dev/null; then echo "$1 has $(grep" ^ [[: space] * $"$1 | wc-l) blank lines." else echo "No blank lines" fi Note: if the success of the command is taken as a condition, the if statement must be followed only by the command itself, not referenced. 3. The multi-branch structure of the if statement: if condition 1, branch 1elif condition 2, branch 2elif condition 3, branch 3. Else branch nfi example: pass a user name to the script: if the user's id number is 0, it shows that this is an administrator; if the user's id number is greater than or equal to 500, it shows that this is an ordinary user; otherwise, it is said to be a system user. #! / bin/bashif [$#-lt 1]; then echo "Usage: `basename $0` username" exit 1fiif! Id-u $1 & > / dev/null; then echo "Usage: `basename $0` username" echo "No this user $1." Exit 2fiif [$(id-u $1)-eq 0]; then echo "Admin" elif [$(id-u $1)-ge 500] Then echo "Common user." else echo "System user." fi3) 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: indicate no line wrapping example: enter the user name, you can return its shellroombinbase read-p "Plz input a username:" userNameif 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 4) conditional testing and case statement case statement: when there are multiple test conditions, the case statement will make the syntax structure clearer: the case variable references the inPATTERN1) the branch 1, the PATTERN2), the branch 2, the PATTERN2, the branch 2, the

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

| a | b: an or bounded: match any character of any length?: match any single character []: any single character within the specified range []: write a script to complete the following tasks, using the following form: 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/bashfile='/var/lock/subsys/script'case $1 instart) 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;; esac4) bash programming loop statement 1) for loop 1, for statement format one 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: traversal element list end example: find the sum of all positive integers up to 100 #! / bin/bashdeclare-I sum=0for I in {1... 100}; do let sum+=$idoneecho $sum2, for statement format 2 for ((initial condition; test condition; modify expression)) The do loop body done first uses the initial conditions and test conditions to judge, if it meets the test conditions, it 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/bashdeclare-I sum=0for ((counter=1;$counter / dev/null; then grep "^ $userName\ >" / etc/passwd | cut-d:-f3 else echo 7 else echo "No such user." Firead-p "Plz enter a username again:" userNamedonewhile Special usage: traversing text file statement structure: while read variable name; do loop body done

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

/ dev/null; then grep "^ $userName\ >" / etc/passwd | cut-d:-f3Magazine 7 else echo "No such user."firead-p" Plz enter a username again: "userNamedone4) Loop Control and shift Loop Control commands: 1) break: exit the loop ahead of time; 2) break [N]: exit the N-layer loop; when N is omitted, exit the loop where the break statement is; 3) continue: end the current cycle ahead of time and enter the next cycle directly 4) continue [N]: advance the current cycle of the N-tier cycle and directly enter the next cycle; 5) endless cycle # whilebody while true; do loop body done# until body 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 logged in, the script terminates; (2) every 5 seconds, check whether the user is logged in #! / bin/bashwhile true; do who | grep "gentoo" & > / dev/null if [$?-eq 0]; thenbreak fi sleep 5doneecho "gentoo is logged." 6) shift

Position parameters can be moved to the left with the shift command, for example, shift 3 means that the original $4 now becomes $1, the original $5 becomes $2, and so on, and the original $1, $2, $3 are discarded, and $0 is not moved. The shift command with no arguments is the equivalent of shift 1.

We know that the number of position variables or command-line arguments must be determined, or when the shell program does not know their number, it can copy all the parameters together to "$*". If the user asks Shell to process the parameters one by one without knowing the number of location variables, that is, $2 after $1, $3 after $2, etc. The value of the variable $1 before the shift command is executed is not available after the shift command is executed.

Example 1 is as follows:

[root@localhost ~] # cat 1. The first parameter is: 1) the number of parameters is: $# "shifts [root @ localhost] # sh 1.sh 1 2 3 4 the first parameter is: 1 the number of parameters is: 4 the first parameter is: 2 the number of parameters is: 3 the first parameter is: 3 the number of parameters is: 2 the number of parameters is: 4 the number of parameters is: 1

As you can see from the above example, each time the shift command is executed, the number of variables ($#) is reduced by 1, and the value of the variable is advanced by one digit.

Example 2 is as follows:

[root@localhost ~] # cat 2. Ne binder Basif [$#-eq 0] thenecho "Usage:2.sh parameter" exit 1fisum=0while [$#-ne 0] dosum= `expr ${sum} + $1`shifter echo "sum is:$ {sum}" [root@localhost ~] # sh 2.sh 10 20 30sum is:60

The shift command also has an important use. Bash defines nine location variables, from $1 to $9, which does not mean that the user can only use nine parameters on the command line, and that more than nine parameters can be accessed with the shift command.

The number of parameters that the shift command moves to at a time is specified by the parameters it takes. For example, when the shell program has finished processing the first nine command-line arguments, you can use the shift 9 command to move $10 to $1.

5) functions of bash programming

Grammatical structure:

Function F_NAME {function body} or F_NAME () {function body} callable: use the function name, where the function name appears, will be automatically replaced with the function Function return value: function execution result return value: print statement is used in the output function of the code: echo, the result returned after the execution of the system command called in the printf function. Return value: default depends on the status 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!

1) the function can receive parameters

Function parameters are called in the same way as script parameters are called in a script:

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

Example:

The requirements are as follows:

1) prompt the user for an executable command

2) get all the library files on which this command depends (use the ldd command)

3) copy the command / mnt/sysroot directory

4) copy the library files to the corresponding directory of / mnt/sysroot

[root@localhost ~] # cat 1. Return target skip-alias skip-alias MNT targetpreCommand / [- d $root] | | mkdir $targetpreCommand () {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:]] +" ` DolibDir= `dirname $lib` [- d ${target} ${libDir}] | | mkdir-p ${target} ${libDir} [- f ${target} ${lib}] | | cp $lib ${target} ${libDir} done} read-p "Plz enter a command:" commanduntil ["$command" = = 'quit']; do if preCommand $command & > / dev/null Then commandCopy $commandPath libCopy $commandPath fi exit 1done [root@localhost ~] # sh 1.shPlz enter a command: cat [root@localhost ~] # ls / mnt/sysroot/bin/cat [root@localhost ~] # ls / mnt/sysroot/bin lib642) signal capture in bash programming

The trap command is used to capture a signal in a shell program, which can then be reacted in three ways:

1) execute a program to process this signal

2) default operation of received signal

3) ignore this signal

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 they are not finished.

[root@localhost ~] # cat 1.shanzhao binbinhquitScript () {echo "Quit..."} trap 'quitScript; exit 5' SIGINTcnetPing () {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}; dobnetPing $1.$mdone} netType= `echo $1 | cut-d "."-f1`if [$netType-ge 1-a $netType-le 126]; thenanetPing $netTypeelif [$netType-ge 128-a $netType-le 191]; thenbnetPing $(echo $1 | cut-dudes.'- f1m2) elif [$netType-ge 192-a $netType-le 223] ThencnetPing $(echo $1 | cut-dudes.'- F1-3) elseecho "Wrong" exit 2fi [root@localhost ~] # sh 1.sh 192.168.1.1192.168.1.1 is down.192.168.1.2 is down.192.168.1.3 is down.192.168.1.4 is down.192.168.1.5 is down.192.168.1.6 is down.192.168.1.7 is down.192.168.1.8 is down .192.168.1.9 is down.192.168.1.10 is up.192.168.1.11 is down.^ CQuit.

After reading the above, do you have any further understanding of the use of bash programming in Linux? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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