bash script syntax Linux

Posted by xepherys on Wed, 15 Dec 2021 09:06:25 +0100

abstract

Shell program is to list the Linux commands that need to be executed by the computer into a file, plus control statements. Interpretive language, which does not need compilation, that is, script file. Bash, SH, CSH, tcsh and KSH are commonly used for user login shells under Linux. They are also shell program interpreters.
Different interpreters have different syntax.
Bash is the default Shell interpreter for Linux.

Create step

  • Create a new file and open touch filename or vim filename
  • The Vim editor enters the insert mode i to edit and write scripts
  • Save and exit wq!
  • Modify file permissions and add executable permissions chmod +x filename
  • Executive document/ filename

Structure and basic grammar

Shell program consists of three parts: the first line, comment line and program body.

  1. First line

It is often indicated in the first line of the Shell program which interpreter this Shell adopts:

#!/bin/bash

If it is not specified, the user login Shell program will be used to explain the execution. Check the user login Shell program name, and the command is

echo $SHELL
  1. Comment line
    Except for the first line, lines beginning with # are comment lines
  2. Program body
    It contains three types of structural statements: sequence, branch and loop structure.

variable

The Shell variable determines the data type according to the assignment type. Each assignment can modify the variable data type again. include

  • Common variables: numeric value, string
  • One dimensional array variable: array subscripts are addressed from 0.
  • Special variables: they are automatically defined and assigned by Bash and cannot be modified by users.
  1. Assignment statement
i=1
str="Hello World"
array=(zhao wang sun li)

Note: there should be no spaces on the left and right sides of the assignment equal sign.

  1. Reference variable: ${variable name}
echo ${i} #Print variable i
j=`exp ${i}+1` #Calculate i+1 and assign it to j
echo ${array[0]}  #Output "zhao"
echo ${array[*]}  #Output "zhao wang sun li"
array[0]=liu  #Change the first element of the array to liu
Array=("${array[*]}")  #Create an array with the same size and value as array array

Note: don't appear spaces casually. It feels completely different from python, otherwise it won't be executed successfully.

  1. For some common special variables, insert the echo variable name in the program body to display the variable value.
Variable namevalue
$$Indicates the current process number, i.e. PID
$?Exit status of the previous command, 0 successfully executed, 1 failed
$#Number of command line parameters, excluding the command itself
$0Command itself
$i0 < I < 9, the i-th parameter of the command line, and {} after two digits
$*All command line parameters

Control statement

Sequential structure:

Execute a series of commands from top to bottom

Branching structure

  1. Judge whether the expression is true or false
test expression
[expression]
Judgment expressionmeaning
! expressionExpression logical value negation
Expression 1 -a expression 2Logical operation and operation
Expression 1 -o expression 2Logical operation or operation
=/!=String comparison
-eqInteger equality
-ge/-gtGreater than / equal to
-le/ltLess than / equal to
-d filefile is a directory. True
-e fileYes, the file is true
-z stringstring is empty and true
  1. Branch statement
if list;
then list;
elif list;
then list;
else list;
fi
case word in 
	[pattern1]) list;;
	[pattern2]) list;;
	*) list
	   list2;;  #Otherwise, execute the list
esac	

Note: multiple statements can appear in a matching mode.

Cyclic structure

#!/bin/bash
#example1 ---for
for i in 1 2 3 4 5;
do
     echo "${i}second|"
done
#Semicolon has no effect
for i in 1 2 3 4
do
     echo "`expr ${i} \* ${i}`second"
done

#example2
for((i=1;i<10;i++));
do
        echo "The first ${i}second"
done

#example3---while
total=0
while read line;
do
	total=(expr ${total} + 1)
done<<(cat /etc/passwd)	  #Display the contents of the / etc/passwd file as the output of the while command (input redirection)
echo ${total}

#example4
#!/bin/bash
PS3="Please select:"  #Display the value of Shell variable PS3, wait for user input, and assign the input value to menu
menus="com|net|org|edu|quit"
IFS="|"   #The value of the Shell variable IFS is used as a separator to cut the menu into multiple items. And add a serial number before each item and display it on the display in the form of column.
select item in ${menus};do
	case ${item} in
		com) echo "Apply com domain";;
		net) echo "Apply net domain";;
		org) echo "Apply org domain";;
		edu) echo "Apply edu domain";;
		quit) break;;
	esac
done

The operation results are as follows:

hazel@hazel-VirtualBox:~/code$ ./gram.bash
1) com
2) net
3) org
4) edu
5) quit
Please select:3
apply org domain
Please select:2
apply net domain
Please select:1
apply com domain
Please select:4
apply edu domain
Please select:5

Loop control statements: break, continue; Both can only appear in the cycle body. The former exits the cycle, and the latter jumps out of the cycle and enters the next cycle.

#example5
#!/bin/bash
for file in *;do
	if[${file}="." -o ${file}=".."]  
	then 
		continue  #For And No treatment
	fi
	[${fil}="123"]&&break  #When file 123 is encountered, the loop will jump out and the & & command sequence connector will be displayed
	cp -r ${file} ${file}.old  #Other files are backed up
done

Shell program debugging

Shell program is an explanatory language. The common method is to display all the executed statements with - x execution program.

bash -x file.bash

When the code is very long (the statement should not exceed 1000 lines), you can add debugging marks before and after the program block to be debugged. Insert set -v before the block and set +v after the block. When debugging, only the execution statements in the debugging block will be printed.