Quick start to shell programming

Time:2020-12-3

Quick start to shell programming

Write a shell script hello.sh

#!/bin/bash 
echo 'hello world!'

Run script hello.sh

#Method 1 
sh hello.sh  

#Method 2 
chmod +x hello.sh 
./hello.sh

#The terminal prints Hello world!
Shell variable

Basic grammar

Define variables: variable name = variable value, and there should be no spaces on both sides of the equal sign. Variable names are usually capitalized.
Delete variable: unset variable name.
Declare static variables: readonly variable name. Static variables cannot be unset.
Use variable: $variable name

$n: $0 represents the command itself; $1 – $9 represents the first to ninth arguments; and curly brackets are used for parameters above 10, such as ${10}.
$*: all parameters in the command line, and all parameters are considered as a whole.
[email protected]: all parameters in the command line, and each parameter is treated differently.
The number of all parameters.

example:Write shell scripts positionPara.sh Output the parameter information of the command line.

#!/bin/bash     
#Output each parameter 
echo $0 $1 $2 
echo $* 
echo [email protected] 
Number of echo parameters=$#

function positionPara.sh

chmod +x positionPara.sh 
./positionPara.sh 10 20

Operation results

./positionPara.sh 10 20 
10 20 
10 20 
Number of parameters = 2

Predefined variables

Basic grammar

$$: PID process number of the current process.
$!: PID process number of the last process running in the background.
$?: the return status of the last command executed. 0 indicates that the execution is correct, and non-0 fails.

example:Write shell scripts prePara.sh Output the parameter information of the command line.

#!/bin/bash     
Echo current process number=$$ 
#& running programs in the background 
./hello.sh & 
Echo the process number of the last process = $! 
Echo last executed command result = $?

Operation results

Current process number = 41752 
Process number of last process = 41753 
The last executed command result = 0 # Hello world!

operator

Basic grammar

$((expression)) or $[expression]
Expr m + n note that there should be spaces between expr operators
expr m – n
Expr *, /,%, respectively represent multiplication, division and remainder

example:

#Method 1 $(()) 
echo $(((2+3)*4))   

#The second method $[], recommended 
echo $[(2+3)*4]  

#Using expr 
TEMP=`expr 2 + 3` 
echo `expr $TEMP \* 4`

Conditional judgment

Basic grammar: [condition] pay attention to the space before and after condition. Non null return 0, 0 is true, otherwise false.

example:

#!/bin/bash 
if [ 'test01' = 'test' ] 
then
     Echo 'is equal to' 
fi  

#Is 20 greater than 10 
if [ 20 -gt 10] 
then
     Echo 'greater than' 
fi  

#Does the file / root / shell / a.txt exist 
if [ -e /root/shell/a.txt ] 
then
     Echo 'exist' 
fi  

if [ 'test02' = 'test02' ] && echo 'hello' || echo 'world' 
then
     If the condition is satisfied, execute the following statement ' 
fi

Operation results

greater than 
hello 
If the condition is satisfied, the following statement will be executed

If judgment

Basic grammar

If [conditional determinant]; then   
    program   
fi

#Or (recommended)
If [conditional judgment]
then
    program
elIf [conditional judgment]
then
    program
fi

example:Write shell program: if the input parameter is greater than 60, output “pass”, otherwise output “fail”

#!/bin/bash
if [ $1 -ge 60 ]
then
    Echo pass
elif [ $1 -lt 60 ]
then
    Echo "fail" 
fi

Case branch

Basic grammar

Case $variable name in
"Value 1")
If the value of the variable is equal to the value of 1, execute the program 1 here
;;
"Value 2")
If the value of the variable is equal to the value 2, execute the program 2 here
;;
... omit other branches
*)
If the variable value is not equal to the value listed above, execute the procedure here
;;
esac

example:When the command line parameter is 1, output “Monday”, 2 output “Tuesday”, other conditions output “other”

case $1 in
"1")
Echo Monday
;;
"2")
Echo Tuesday
;;
*)
Echo other
;;
esac

For loop

Basic grammar

#Grammar 1
For variable name in value 1 value 2 value 3
do
    program
done

#Grammar 2
For ((initial value; loop control condition; variable change))
do
    program
done

example:

1. Print the parameters entered from the command line.

#!/bin/bash  

#Use$* 
for i in "$*" 
do     
    echo "the arg is $i" 
done 
echo "=================="  

#[email protected] 
for j in "[email protected]" 
do     
    echo "the arg is $j" 
done

Operation results

the arg is 1 2 3 
================== 
the arg is 1 
the arg is 2 
the arg is 3

2. Output the value from 1 to 100.

#!/bin/bash 
SUM=0  
for ((i=1;i<=100;i++)) 
do     
    SUM=$[$SUM+$i] 
done 

echo $SUM

While loop

Basic grammar

While
do
    program
done

example:Output a value from 1 to 100.

#!/bin/bash
SUM=0
i=0

while [ $i -le $1 ]
do
    SUM=$[$SUM+$i]
    i=$[$i+1]
done       
echo $SUM

Read console input

Basic grammar

Read (option) (parameter)
option

  • -p: Specifies the prompt when reading values
  • -t: Specifies the time (in seconds) to wait for a value to be read. If it is not entered within the specified time, it is no longer waiting.

parameter

  • Variable name: the name of the variable that reads the value

example:Read the console and enter a num value.

#!/bin/bash

Read - P "please enter a number num1 = num1
Echo "the value you entered for num1 is $num1"

Please enter a number in 10 seconds num2 = num2
Echo "the value you entered for num2 is $num2"

Operation results

Please enter a number num1 = 10
The value you entered for num1 is: 10
Please enter a number num2 = 20 in 10 seconds
The value you enter for num2 is: 20

function

1. System function

Basic grammar

Basename, to delete all parts (including /) before the last / of the path, which is often used to get the file name.
Basic grammar
basename [pathname] [suffx]
basename [string] [suffx]
If suffx is specified, the suffix part of pathname or string is also deleted.

Dirname, to delete all parts (including /) after the last / of the path, which is often used to get the file path.
Basic grammar
dirname pathname
If the path does not contain /, it returns’. ‘(current path).

example:

# basename /usr/bin/sort  
sort  

# basename include/stdio.h  
stdio.h  

# basename include/stdio.h .h 
stdio

# dirname /usr/bin/  
/usr  

# dirname dir1/str dir2/str 
dir1 
dir2  

# dirname stdio.h 
.

2. User defined function
Basic grammar

[ function ] funname[()]
{
    Action;
    [return int;]
}

#Call
Funname Parameter1 parameter2

example:Calculate the sum of the two input parameters.

#!/bin/bash

function getSum(){
    SUM=$[$n1+$n2]
    echo "sum=$SUM"
}   

"Please enter the first parameter N1:" N1
Read - P "please enter the second parameter N2:" N2

#Call the getsum function
getSum $n1 $n2