3, shell Scripting

Posted by Chalks on Sun, 20 Feb 2022 15:02:55 +0100

shell command

  • The commands that come with the Shell are called built-in commands, which can be implemented through functions inside the Shell. After the Shell is started, the code corresponding to these commands (function body code) is also loaded into memory, so using built-in commands is very fast. It is essentially a self-contained function
  • More commands are external applications, and one command corresponds to one application. Running external commands starts a new process, so the efficiency is much worse than that of built-in commands. It is essentially an application.
  • After the user enters a command, the Shell first detects whether the command is a built-in command. If so, execute it. If not, detect whether there is a corresponding external program: if so, turn to the external program and return to the Shell after execution; If not, an error will be reported to tell the user that the command does not exist.

**Built in commands: * * too many built-in commands should not be used. Too many built-in commands will lead to the expansion of the shell program itself, which will occupy more memory after running the shell program. Shell is a memory resident program. Occupying too much memory will affect other programs. Only the most commonly used commands are justified as built-in commands, such as cd, kill, echo, etc.

**External command: * * use echo command to output the value of PATH variable, which saves the search PATH of Shell external command.

swiler@swiler-VirtualBox:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

The application is converted to shell external command operation

Create hello C documents,

gcc commandUsed to compile c and c + + files - c compile and assemble without linking
-SCompile without assembly and linking
-EPretreatment
-vThe compiler code is also displayed
-O < File >Import the output to the specified file
-X < language >Specify language
–helpdisplay help information
–versiondisplay version information

If gcc is not installed, just install it. Run $sudo apt install gcc

After installation, execute gcc output, and you can see the hello file output

Transfer hello to

This converts an application into a shell external command operation.

The specific steps are as follows:

# hello_world.c the content of the document is
vim hello_world.c  
#Press i to enter the input mode

#include 

int main ()
{

printf("Hello World ");

return 0;
}

# After pressing ESC: wq save exit

# Compile and then input the output into the hello file
gcc -o hello hello_world.c 
# implement
./hello
# Display content: Hello World

Legitimate shell parser

Four kinds: sh/ bash/ rbash/ dash

View sh parser

Write a shell script

#Create shell script
swiler@swiler-VirtualBox:~$ sudo vi hello.sh

#In file
#!/bin/bash
echo "hello,world!"

#Modify file permissions
swiler@swiler-VirtualBox:~$ sudo chmod 777 hello.sh
#View directory
swiler@swiler-VirtualBox:~$ ll
#Observable
-rwxrwxrwx  1 root   root     33 2 December 9:44 hello.sh*
#There are four startup modes as follows:

shell startup mode

The four startup modes are different in terms of environment variables, which will not be discussed for the time being

shell script syntax

Variable related operations

Define variables

  • variable=value
#stay vi In editor#
#Specifies the parser used by the shell script
#!/bin/bash
#Define a variable and assign it directly. There can be no spaces around the equal sign. It is applicable to the case that the value of the variable has no spaces or characters
var=1234
#Add $sign to use variables and output them directly with echo
echo "$var"

Execute, terminal output 1234

  • variable='value'
#stay vi In editor#
#Specifies the parser used by the shell script
#!/bin/bash
#Define a variable, enclosed in single quotation marks, with no spaces around the equal sign
var='123 454'
#Add $sign to use variables and output them directly with echo
echo "$var"

Execute, terminal output 123 454

  • variable="value"
#stay vi In editor#
#Specifies the parser used by the shell script
#!/bin/bash
#Define a variable, enclosed in double quotation marks, with no spaces around the equal sign
var="123 454"
#Define a variable, enclosed in double quotation marks, with no spaces around the equal sign
var1="${var}abcd"
#Add $sign to use variables and output them directly with echo
echo "$var1"

##If will var1="${var}abcd"Change to var1='${var}abcd',Then the output content is ${var}abcd##

Execute, terminal output 123 454abcd

Pay attention to the difference between single quotation marks and double quotation marks. The contents in single quotation marks are WYSIWYG, that is, everything in single quotation marks is output as characters; Double quotation marks can distinguish references to other variables.

Use variables

  • $variable
  • ${variable}

Assign the result of the command to a variable

  • variable=`command`
#!/bin/bash
var=`pwd`
echo "$var"
#Execute the pwd command to immediately know the absolute path name of the current working directory.

  • variable=$(command)
#!/bin/bash
var=$(pwd)
echo "$var"

Delete variable

  • unset
#!/bin/bash
var="123 454"
var1="star"
echo "${var1}${var}"
#Without unset var, the first two variables are output
unset var	
#After unset var, the var variable is not output, only var1 is output
echo "${var1}${var}"

Special variable

variablemeaning
$0The file name of the current script.
$n(n≥1)Parameters passed to a script or function. n is a number indicating the number of parameters. For example, the first parameter is $1 and the second parameter is $2.
$#The number of arguments passed to the script or function.
$*All parameters passed to a script or function.
$@All parameters passed to a script or function. When enclosed in double quotation marks, "$@ is slightly different from $*
$?Exit status of the previous command or get the return value of the function.
$$Current Shell process ID. For Shell scripts, it is the process ID where these scripts are located.
#!/bin/bash

var="123 454"
var1="star"
echo "${var1}${var}"	#Reference and output variables
unset var
echo "${var1}${var}"	#Reference and output variables

echo "$0"				#The file name of the current script

echo "$1"				#The parameter $1 passed to the script or function is assigned on the console
echo "$2"				#The parameter $2 passed to the script or function is assigned on the console

echo "$#"				#The number of parameters passed to the script or function

echo "$*"				#All parameters passed to a script or function
echo "$@"				#All parameters passed to a script or function

echo "$?"				#Exit status of the previous command or get the return value of the function

echo "$$"				#Current Shell process ID

exit 11					#Set function return value

Output result:

String splicing

And discharge

#!/bin/bash

var="star "
var1=${var}sun	#String splicing
echo ${var1}
#Or output it like this: echo "$var1"
#Or output it like this: echo "${var1}"

Read the data entered from the keyboard

read

#!/bin/bash

read -p "input a:" a
read -p "input b:" b

echo "${a}"
echo "${b}"

Execution result:

Exit the current process

exit

Mathematical operations on integers

(())

#!/bin/bash

#Enter values for a and b
read -p "input a:" a
read -p "input b:" b

#Execute a+b and assign it to var
var=$(( a+b ))

#Output var to console
echo "${var}"

Execution result:

Logic and / or

command1 && command2
command1 || command2

Check whether a condition is true

test expression and [expression]

OptionsAction (0 is true, 1 is false)
-eqJudge whether the values are equal
-neJudge whether the values are not equal
-gtJudge whether the value is greater than
-ltJudge whether the value is less than
-geJudge whether the value is greater than or equal to
-leJudge whether the value is less than or equal to
-z strJudge whether the string str is empty
-n strJudge whether the string str is non empty
=And==Determine whether the string str is equal
-d filenameJudge whether the file exists and whether it is a directory file.
-f filenameJudge whether the document exists and whether it is an ordinary document.
#!/bin/bash

read -p "input a:" a
read -p "input b:" b

echo "0 is true,1 is false"
#Judge whether the values are equal
echo "test -eq a&&b"
test $a -eq $b && echo "a=b"
#Judge whether the values are not equal
echo "test -eq a||b"
test $a -eq $b || echo "a!=b"
#Judge whether the values are not equal
echo "test -ne"
test $a -ne $b && echo "a!=b"
#Judge whether the value is greater than
echo "test -gt"
test $a -gt $b && echo "a>b"
#Judge whether the value is less than
echo "test -lt"
test $a -lt $b && echo "a<b"
#Judge whether the value is greater than or equal to
echo "test -ge"
test $a -ge $b && echo "a>=b"
#Judge whether the value is less than or equal to
echo "test -le"
test $a -le $b && echo "a<=b"

​ a>b / a<b / a=b

Judge whether the file exists and whether it is a directory file

#!/bin/bash
read -p "input a:" a
[ -d $a ] && echo "${a}"

Judge whether the file exists and whether it is an ordinary file

#!/bin/bash
read -p "input a:" a
[ -f $a ] && echo "${a}"

The Conduit

definition

Generally, when we operate, there are many commands, but we only want some of them, so we can use the pipeline.
Pipeline is a very important way of communication in Linux. It connects the output of one previous result directly to the input of another. It is usually used in cooperation with grep.

**Command: * * command1 | command2

if statement

if statement

if condition
then
​ statement(s)
fi

if else statement

if condition
then
statement1
else
statement2
fi

if elif else statement

if condition1
then
statement1
elif condition2
then
​ statement2

......
else
statementn
fi

#!/bin/bash
#Enter a and b
read -p "input a:" a
read -p "input b:" b

if [ $a -eq $b ]		#If a=b
then
        echo "a=b"
elif [ $a -gt $b ]		#If a > b
then
        echo "a>b"
else					#If a < B
        echo "a<b"
fi

case in statement

case expression in
​ pattern1)
​ statement1
​ ;;
​ pattern2)
​ statement2
​ ;;
​ pattern3)
​ statement3
​ ;;
​ ......
​ *)
​ statementn
esac

#!/bin/bash
read -p "input a:" a
case $a in
	1)
		echo "a=1"
		;;
	2)
		echo "a=2"
		;;
	3)
		echo "a=3"
		;;
	*)
		echo "a=other"
		;;
esac

Output result:

for in loop

for variable in value_list
do
​ statements
done

value_list value

  • Give specific values directly
  • Give a value range
#!/bin/bash
#read -p "input a:" a
#read -p "input b:" b

for n in {1..10}
do
        echo "$n"
done

#The effect is the same as above
#for n in 1,2,3,4,5,6,7,8,9,10
#do
#        echo "$n"
#done

Results: output 1 ~ 10, ten numbers.

  • Use the execution result of the command
  • Use Shell wildcards
#!/bin/bash
#read -p "input a:" a
#read -p "input b:" b

for n in $(ls /bin/*sh)
do
	echo "$n"
done
#The shell parser in the bin directory traverses it

result

  • Use special variables$*
#!/bin/bash
#read -p "input a:" a
#read -p "input b:" b
for n in $*	
#Or for n in$@		
#Or for n in "$@"
do
	echo "$n"
done

result:

  • Use special variable "$*"
#!/bin/bash
#read -p "input a:" a
#read -p "input b:" b
for n in "$*"
do
	echo "$n"
done

result:

while loop

while condition
do
​ statements
done

#!/bin/bash
n=0
while (( n < 10))
do
        echo "${n}"
        n=$((n+1))
done

result:

Define function

function name() {
​ statements
​ [return value]
}

#!/bin/bash
#Define a function
function my_name(){
	echo "swiler"
}
#Call this function
my_name

Topics: Linux Ubuntu Embedded system bash