shell basic learning

1. Basis

  • The following program runs on a subsystem of Windows
  • Ls/bin/sh-al obtains lrwxrwxrwx 1 root 4 Aug 26 20:44/bin/sh -> dash Run sudo ln-fs/bin/bash/bin/sh to replace the compiler with SH
  • Create directory mkdir shell
  • Create/Enter File vim t1.sh
  • Press i to enter edit mode, press Esc to exit edit mode, press: x to exit
  • sh t1.sh run file
  • clear Empty Panel
  • Set executable permissions chmod +x test.sh for scripts

2. Variables

  • Define variables directly. There can be no spaces between variable names and equal signs
  • Use a defined variable ${variable name}. Curly brackets can be omitted but are best added
your_name="tom"
echo ${your_name}
your_name="alibaba"
echo ${your_name}
  • Define variables as read-only variables using the raedonly command
your_name="tom"
echo $your_name
readonly your_name
your_name="test"
#tom
#t1.sh: 4: your_name: is read only
  • Use the unset command to delete variables, but not read-only variables
s="test"
unset s
echo $s
#No output, no error

1. Strings

  • String single and double quotation marks are fine, preferably double quotation marks
s="Tom"
str="hello,\"${s}\"!\n"
echo $str
#hello,"Tom"!
  • Split string, invalid variable in single quotation string
your_name="runoob"
# Use double quotation marks to stitch together
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting  $greeting_1
# Stitching using single quotation marks
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2  $greeting_3

#hello, runoob ! hello, runoob !
#hello, runoob ! hello, ${your_name} !
  • Use # to get the length of the string. The program description below \n has a length of 2
s="Tom"
str="hello,\"${s}\"!\n"
echo ${#str}
str="hello,'Tom'!"
echo ${#str}
#14
#12
s="'"
echo ${#s}
s='"'
echo ${#s}
#1
#1
s="\n"
echo ${#s}
#2
  • Extract a string and intercept a 3-length string starting with a character subscripted to 1
s="string"
echo ${s:1:3}
#tri
  • Find string, return position counts from 1
s="string"
echo `expr index "$s" s`
#1

2. Arrays

  • bash supports one-dimensional arrays, but does not support multi-dimensional arrays. Parentheses denote arrays and elements are separated by spaces
  • Continuous subscripts may not be used, and the range of subscripts is unlimited
  • Read the array ${array name [subscript]} and use @ to get all elements of the array, the same length as the string
a[0]=1
echo ${a[0]}
a[3]=2
echo ${a[3]}
echo ${a[@]}
a[99]=111
echo ${#a[@]}
#1
#2
#1 2
#3

3. Comments

  • Single-line comments use the same #as Py
  • Multiline comment, EOF can also use other symbols
:<<EOF
 Note Content...
Note Content...
Note Content...
EOF
:<<'
Note Content...
Note Content...
Note Content...
'

:<<!
Note Content...
Note Content...
Note Content...
!

3. Transfer parameters

  • When executing a Shell script, pass the parameter $n to the script, the zero parameter is the file name, and no pass is required
echo "Shell Pass-through parameters"
echo "Execution file name:$0"
echo "The first parameter is:$1"
#Enter sh t1.sh 1
#Shell pass parameters
#Execution file name: t1.sh
#The first parameter is:1
  • There are also special characters to handle parameters
Parameter ProcessingExplain
$#Number of parameters passed to the script
$*Displays all parameters passed to the script in a single string.For example,'$*'enclosed with'', output all parameters in the form of'$1 $2...$n'.
$$Current process ID number of the script running
$!ID number of the last process running in the background
$@Same as $*, but with quotation marks and each parameter returned in quotation marks. For example,'$@'with', with'$1'. 2 " ... " 2" ... " 2'...'n' to output all parameters.
$-Displays the current options used by Shell, and set command The functions are the same.
$?Show the exit status of the last command.0 for no errors and any other values for errors.
echo "Shell Pass-through parameters"
echo "The first parameter is $1"

echo "Number of parameters $#"
echo "The parameters passed are displayed as a string $*"
#Enter sh t1.sh 1234 123 121
#Shell pass parameters
#The first parameter is 1234
#Number of parameters is 4
#The passed parameter displays 1234 123 121 as a string
  • Both $* and $@ refer to all parameters, but the difference is that assuming the script runs with three parameters 1,2,3, * equivalent to "1 2 3" (one parameter), @ equivalent to "1" "2" "3" (three parameters)
echo "\$*Demonstration"
for i in "$*"; do
        echo $i
done

echo "\$@Demonstration"
for i in "$@" ;do
        echo $i
done
#Enter sh t1.sh 1 2 3 4 1
#$* Demo
#1 2 3 4 1
#$@Demo
#1
#2
#3
#4
#1

4. Operators

1. Arithmetic Operators

  • Native bash does not support simple mathematical operations, but it can be done with other commands, such as awk and expr.expr, which are most commonly used, but there must be a space between the expression and the operator
val=`expr 2 + 2`
echo "Sum of two numbers is ${val}"
#Sum of two numbers is 4
  • Here are the common arithmetic operators, assuming that variable a is 10 and variable B is 20:
operatorExplainGive an example
+addition`expr $a + $b` results in 30.
-subtraction`expr $a - $b` results in-10.
*multiplication`expr $a * $b` results in 200.
/division`expr $b / $a` results in 2.
%Remaining`expr $b%$a`The result is 0.
=assignment\a=$b assigns a value to variable B.
==Equal. Used to compare two numbers, the same returns true.[$a == $b]Returns false.
!=Not equal. Used to compare two numbers, different returns true.[$a!= $b] Returns true.
  • Conditional expressions must be placed between square brackets and have spaces
a=10
b=20

var=`expr $a + $b`
echo "a+b=$var"
var=[ $a == $b ]
echo "$var"
#a+b=30
#t1.sh: line 6: 10: command not found
#30
  • There are no Boolean variables in the Shell

2. Relational Operators

  • Relational operators only support numbers, not strings, unless the value of a string is a number
  • Below are the common relational operators, assuming that variable a is 10 and variable B is 20:
operatorExplainGive an example
-eqDetects whether two numbers are equal, and returns true if they are equal.[$a-eq $b] returns false.
-neDetects if two numbers are not equal and returns true if they are not equal.[$a-ne $b] returns true.
-gtDetects if the number on the left is greater than that on the right and returns true if it is.[$a-gt $b] returns false.
-ltDetects if the number on the left is less than the number on the right and returns true if it is.[$a-lt $b] returns true.
-geDetects if the number on the left is greater than or equal to the number on the right, and returns true if it is.[$a-ge $b] returns false.
-leDetects if the number on the left is less than or equal to the number on the right, and returns true if it is.[$a-le $b] returns true.
a=10
b=20

if [ $a -eq $b ]
then
        echo "$a -eq $b : a Be equal to b"
else
        echo "$a -eq $b : a Not equal to b"
fi
#10-eq 20: a does not equal b

3. Boolean Operators

  • Below are the common Boolean operators, assuming variables a are 10 and B are 20:
operatorExplainGive an example
!Not an operation, the expression true returns false, otherwise it returns true.[! false] Returns true.
-oOr, an expression that is true returns true.[$a-lt 20-o $b-gt 100] Returns true.
-aAnd operation, both expressions are true to return true.[$a-lt 20-a $b-gt 100] Returns false.
a=10
b=20

if [ $a != $b ]
then
        echo "$a != $b : a Not equal to b"
else
        echo "$a != $b : a Be equal to b"
fi
#10!=20: A is not equal to b

4. Logical Operators

  • Assume that variable a is 10 and variable B is 20:
operatorExplainGive an example
&&Logical ADD[[$a-lt 100 & & &$b-gt 100]] Returns false
||Logical OR[[$a-lt 100 || $b-gt 100]] Returns true
a=10
b=20

if [ $a = 100 || $b = 100]
then
        echo "$a = 100 || $b = 100 : a = 100 or b = 100"
else
        echo "$a = 100 || $b = 100 : a b Neither equals 100"
fi
#10 = 100 || 20 = 100: a B is not equal to 100

5. String Operators

  • Below are the common Boolean operators, assuming that variable a is "abc" and variable b is "efg":
operatorExplainGive an example
=Detects whether two strings are equal, and returns true if they are equal.[$a = $b] returns false.
!=Detects if two strings are not equal and returns true if they are not equal.[$a!= $b] Returns true.
-zDetects whether the string length is 0, returns true for 0.[-z $a] returns false.
-nDetects if the string length is not zero and returns true for zero.[-n'$a'] returns true.
$Detects whether a string is empty, returns true instead of empty.[$a] returns true.
a="abc"
b="efg"
if [ -z $a ]
then
        echo "-z $a : Character string a Length 0"
else
        echo "-z $a : Character string a Length not zero"
fi
#-z abc: string a length is not zero

6. File Test Operators

  • The File Test Operator is used to detect various properties of Unix files
OperatorExplainGive an example
-b fileDetects if the file is a block device file and returns true if it is.[-b $file] returns false.
-c fileDetects if the file is a character device file and returns true if it is.[-c $file] returns false.
-d fileDetects if the file is a directory and returns true if it is.[-d $file] returns false.
-f fileDetects if the file is a normal file (neither a directory nor a device file), and returns true if it is.[-f $file] returns true.
-g fileDetects if the file has a SGID bit set and returns true if it does.[-g $file] returns false.
-k fileDetects if the file has a Sticky Bit set and returns true if it does.[-k $file] returns false.
-p fileDetects if the file is a named pipe and returns true if it is.[-p $file] returns false.
-u fileDetects if the file has a SUID bit set and returns true if so.[-u $file] returns false.
-r fileDetects if the file is readable and returns true if it is.[-r $file] returns true.
-w fileDetects if the file is writable and returns true if it is.[-w $file] returns true.
-x fileDetects whether the file is executable and returns true if it is.[-x $file] returns true.
-s fileDetects if the file is empty (if the file size is greater than 0), returns true if it is not empty.[-s $file] returns true.
-e fileDetects the existence of files, including directories, and returns true if so.[-e $file] returns true.

Other checkers:

  • -S: Determine if a file is socket.
  • -L: Detects whether a file exists and is a symbolic link.
file="/shell/t1.sh"
if [ -r $file ]
then
        echo "File Readable"
else
        echo "File is not readable"
fi
#File is not readable

5. echo command

  • echo is used for string output, double quotes can be omitted
  • read reads a line from standard input and assigns the value to the specified variable
read s
echo "$s is a test"
#a
#a is a test
  • Show line breaks, open escape with -e
echo -e "OK\n"
echo "test"
#OK
#
#test
  • Show line breaks when escape is turned on\c does not wrap
echo -e "OK \c"
echo "test"
#OK test
  • Display results directed to file
echo -e "OK \c" > myfile
  • Output string as is, without escape or taking variables (in single quotes)
read name
echo '$name\"'
#n
#$name\"
  • Show command execution results
echo `date`
#Sat Aug 28 09:02:19 CST 2021

6. Pritf commands

  • Pritf mimics printf in C library, default printf does not add line breaks
echo "hello"
printf "hello\n"
#hello
#hello
printf "%-10s %-8s %-4s\n" Name Sex Weight
printf "%-10s %-8s %-4.2f\n" Yang Sen Male 50.2123
#Name Sex Weight
#Yang Sen Male 50.21

Use it to see printf in C

7. test command

  • The test command checks whether a condition is valid and can be tested in three ways: numeric, character, and file.
parameterExplain
-eqEqual is true
-neTrue if not equal
-gtTrue if greater than
-geTrue if greater than or equal to
-ltTrue if less than
-leTrue if less than or equal to
n1=100
n2=100
if test $[n1] -eq $[n2]
then
        echo 'Two numbers are equal'
else
        echo 'Two numbers are not equal'
fi
#Two numbers are equal

[] in the code can perform basic arithmetic operations

n1=100
n2=1

r=$[n1+n2]
echo $r
#101
  • String test and string comparison parameters are different, spaces are ignored in the test
parameterExplain
=Equal is true
!=Unequal is true
-z stringTrue if the length of the string is zero
-n stringTrue if the length of the string is not zero
n1="100 "
n2="100"

if test $n1 = $n2
then
        echo 'String equality'
else
        echo 'Strings are not equal'
fi
#String equality
#If test = without spaces on both sides, test: 100: unary operator expected
s1="1"
s2=" 1"
if test $s1 = $s2
then
        echo "String spaces ignored"
else
        echo "Spaces are also characters"
fi
#String spaces ignored
  • The file test parameters are as follows
parameterExplain
-e File NameTrue if file exists
-r file nameTrue if the file exists and is readable
-w file nameTrue if file exists and writable
-x file nameTrue if the file exists and is executable
-s file nameTrue if the file exists and has at least one character
-d file nameTrue if the file exists and is a directory
-f file nameTrue if the file exists and is a regular file
-c file nameTrue if the file exists and is a character-specific file
-b file nameTrue if the file exists and is a block-specific file
if test -e t1.sh
then
        echo File Exists
else
        echo file does not exist
fi
#File Exists
  • You can use -a, -o,!Connect Test Conditions
if test -e t1.sh -o -e no.sh
then
        echo At least one file exists
else
        echo Neither file exists
fi
#At least one file exists

8. Process Control

  • Shell's process control cannot be empty

1.if-then-elif-then-fi

  • if statement must have a fi end and can be used;Write the statement block as a line
a=10
b=20
if [ $a == $b ]
then
        echo "="
elif [ $a -gt $b ]
then
        echo ">"
elif [ $a -lt $b ]
then
        echo "<"
else
        echo "No qualifications met"
fi
#<
  • if is often used in conjunction with the test command
a=$[2*3]
b=$[1+5]
if test $[a] -eq $[b]
then
        echo =
else
        echo !=
fi
#=

2.for var in i1,i2... -do-done

  • When a variable value is in the list, the for loop executes all commands once, and the command can be any valid Shell command and statement. The in list can contain substitutions, strings, and file names
for str in this is a string
do
        echo $str
done
#this
#is
#a
#string

3.while condition-do-done

  • while can be used to read information, enter Ctrl+D to end the loop
while read str
do
        echo $str
done
#I like you!
#I like you!
while :
do
        echo Infinite loop
done

4.until condition-do-done

  • The untile and while loops are handled in the opposite way
a=0
until [ ! $a -lt 10 ]
do
        echo $a
        a=`expr $a + 1`
done
#0
#1
#2
#3
#4
#5
#6
#7
#8
#9

5.case i in ... -)-;;-*)-esac

  • Case...easc is similar to switch...case, after successful matching all commands begin to execute until
read num
case $num in
        1) echo 'Input 1';;
        2) echo 'Input 2';;
        test) echo 'Input Test';;
        *) echo 'No input 1,2,test';;
esac
#3
#No input 1,2, test
  • Jump out of the loop using continue and break is similar to Py
#Input Number
#3
#The number is 3
#Input Number
#1
#Number 1
#Input Number
#7
#The number is not 1,2,3

9. Functions

  • The function definition in Shell is similar to that in Py except that braces are added
fun()
{
        echo "First function"
}
echo "Function Start Execution"
fun
echo "Function Execution Completed"
#Function Start Execution
#First function
#Function Execution Completed
  • The return value of a function passes through $after calling the function?To get
fun()
{
        echo "First Number"
        read a
        echo "Second number"
        read b
        echo "The two numbers are $a $b"
        return $(($a + $b))
}
fun
echo "Enter number sum as $?"
:<< !
First Number
1
 Second number
4
 The two numbers are 1 4
 Enter number and 5
!
  • In Shell, you can pass parameters when calling a function, get the value of the parameter internally by $n, starting with n
fun()
{
        echo "First Number $1"
        echo "Second number $2"
        echo "Share $#Parameters "
        return $(($1 + $2))

}
fun 1 23 4 1
echo "Enter the sum of the first two numbers as $?"
#First Number 1
#Second number 23
#There are 4 parameters
#Enter the first two numbers plus 24
  • Note that $10 cannot get the tenth parameter because there is a misconception of $1 that you must use
Parameter ProcessingExplain
$#Number of parameters passed to a script or function
$*Display all parameters passed to the script as a single string
$$Current process ID number of the script running
$!ID number of the last process running in the background
$@Same as $*, but quoted and returned each parameter in quotation marks.
$-Displays the current options used by Shell as set commands.
$?Show the exit status of the last command.0 for no errors and any other values for errors.

10. Other

1. Input\Output Redirection

  • https://www.runoob.com/linux/linux-shell-io-redirections.html

2. File contains

  • https://www.runoob.com/linux/linux-shell-include-file.html

Tags: shell

Posted on Thu, 30 Sep 2021 12:45:33 -0400 by khan kaka