Write a Hello world

[root@VM_234_23_centos ~]# vim hello.sh
---hello.sh
echo "Hello world!"

----
[root@VM_234_23_centos ~]#sh hello.sh
Hello world!
Copy the code

Implement way

There are two ways to do this

  • Sh: for example, # sh hello.sh actually uses the /bin/bash program, which executes the instructions in the script within a new bash environment! Create a bash subroutine for the current process. Bash, like multithreading, is a child thread, and private variables do not affect variables in the main process.
  • Source: Execute in this bash program, all operations take effect in the original bash. Bash is operating in the same process, and variable definitions and changes affect bash.

Determine type

The test instruction

This command can be used to check certain files or related properties. More commonly, after entering man test on the command line, you can see the related parameters.

Test does not return execution results
[root@VM_234_23_centos ~]# test -e index.html
We can judge the success of the instruction according to the last execution result
[root@VM_234_23_centos ~]# echo $?
0
# about && (and) | | (or) operation
The PS shell does not have a precedence of instructions, so remember to include parentheses or write order when processing logical operations
[root@VM_234_23_centos ~]# test -e index.html && echo "file exist" || echo "Not exist"
file exist
Copy the code

Shell script default functions ($0,$1…)

If you actually write an instruction, you can probably figure out where the default function is

/path/to/scirptname parm1 parm2 parm3 parm4
       $0           The $1    $2   $3   $4
Copy the code
  • $0: script file name
  • $1: The first parameter
  • $2: The second parameter
  • $# : indicates the number of parameters
  • $@ : it means the parameter list, such as the above, said [” $1 “, “$2”, “$3”, “$4”], each variable is independent.
  • $* : indicates [“$1c$2c$3c$4”], where C is the separator character and the default space bar

Shift: causes the parameter variable number to shift

Feel offsets like moving subscripts of an array of parameters

Write a program

[root@VM_234_23_centos ~]vim shift_test.sh
echo "This program script name is : $0"
echo "Before Shift"
echo "This program paramters number is : $#"
echo "Your whole paramter is : $@"
echo "The first number is : The $1"
echo "After Shift"
shift 3
echo "Your whole paramters number is : $#"
echo "Your whole paramter is : $@"
echo "The first number is : The $1"
echo "End"Finally, save the configuration and exit :wqCopy the code

Let’s see what happens

[root@VM_234_23_centos ~]
sh shift_test.sh parm1 parm2 parm3 parm4 parm5 parm6
This program script name is : shift_test.sh   # file name
Before Shift
This program paramters number is : 6 # number of parameters
Your whole paramter is : parm1 parm2 parm3 parm4 parm5 parm6  # all variables
The first number is : parm1
After Shift     # After moving
Your whole paramters number is : 3 # The subscript of the parameter has been moved, and the total number has decreased accordingly
Your whole paramter is : parm4 parm5 parm6
The first number is : parm4
End
Copy the code

Conditional judgment

Using the if… then

If the condition is true, execute the statement after then in the following format:

if[c]. the xxxx# Command work content that can be carried out when the condition is established
fi  # in turn indicates the end of the if statement
Copy the code

In the conditional judgment formula, when there are multiple conditions to be judged, the following two are commonly used:

  • && represents the AND
  • | | represents the OR

Multiple judgment

There are two scenarios: success or failure

# Judgment of a condition, divided into successful and failed execution (else)
if[c].thenSuccessful statementelseThe statement that is executed when the condition failsfi
Copy the code

Multiple conditions

if[Condition 1];thenThe statement executed when condition one succeedselif[Condition 2];thenThe statement executed when condition two succeedselseExecute this statement if none of the above conditions existfi
Copy the code

case… esac

Start with CASE and end with ESAC. The specific syntax is as follows

case ${variable name} in
  "First variable content")  # It is recommended to enclose the contents of each variable in double quotation marks.Procedures section;;Use two consecutive semicolons at the end of each category
  "Second variable content") program segment; *)# The last variable content will use * to represent all other values (sort of like the default node HHH)If none of the above statements are executed, this section will be executedexit1;;esac  # End of case, [reverse]
Copy the code

The function function

Function, similar to a fragment wrapper that defines an instruction to execute, for example:

function fname() {program segment}Copy the code

Note: Shell script is executed from top to bottom, from left to right, so function Settings in shell script must be at the beginning of the program.

For example, define a simple print function and print with a case selection of the input arguments:

[root@VM_234_23_centos ~]vim test.sh
function printit() {
    echo  "Your choice is "
}

echo "This program will print yout selection !"
case The ${1} in
  "one")
	printit; echo The ${1} | tr 'a-z' 'A-Z' # Change case
	;;
  "two")
	printit; echo The ${1} | tr 'a-z' 'A-Z'
	;;
  *)
	echo "The param not match"
	;;
esac
Copy the code

After saving, execute the code:

[root@VM_234_23_centos ~]sh test.sh one
This program will print yout selection !
Your choice is
ONE
Copy the code

It is also mentioned in the book that the function of one line of code does seem a bit weak, but it can encapsulate multiple instructions and become a module, which abstracts repetitive code and improves code cleanliness.

Function also has built-in variables, much like shell script, with the function name $0 followed by $1,$2… , but only within the function


Circulation Loop

A loop can continue to execute a section of the program until a condition set by the user is fulfilled.

While do done, until do done

① when the condition is true, the loop is continued until the condition is not true

while [condition] # The states in parentheses are the judgements
do              # marks the beginning of the cycleProcedures sectiondone            # marks the end of the loop
Copy the code

(2) : until

until [condition]
doProcedures sectiondone
Copy the code

The difference is that while evaluates the condition at least once, while until executes the segment directly and evaluates the condition before the second loop.

for… do… Done (fixed loop)

This loop knows how many times to loop, and usually the body of the loop is an array that iterates through each parameter.

① : Foreach form

for var in con1 con2 con3 ...
doProcedures sectiondone
Copy the code

② : Custom step size processing

for((initial value; Limit; Execution step))doProcedures sectiondoneSuch as:for (( i = 1; i < ${number}; i = i + 1 ))
doProcedures sectiondone
Copy the code

So let’s see how arrays are written

As with any array, each value in the array is specified by a subscript, again starting at 0

[root@VM_234_23_centos ~]vim list.sh
function print_list() {
   local numbers        Declare local variables
   numbers=(`echo "$@"`) Return to array, otherwise $1 will be treated as a single character
   size=${#numbers[*]}
   for (( i=0; i<${size}; i=i+1 ))
   do
         echo "The ${i} number is ${numbers[i]}"
   done
}
list=(0 1 2 3 4)
print_list "${list[*]}" Pass an array to the method[root@VM_234_23_centos ~]sh list.sh The 0 number is 0 The 1 number is 1 The 2 number is 2 The 3 number is 3 The 4 number  is 4Copy the code

The above example describes how to define a function, pass an array as a parameter, convert a group of passed arguments to a function, and pass an array through a for loop


The resources

1. “Birdman’s Private Linux Dishes – Basics”