Shell basic syntax

Keywords: Linux vim

1, Variable

1. When defining a variable, the variable name does not add a dollar sign

2. Naming can only use English letters, numbers and underscores, and the first character cannot start with a number.

3. There can be no space in the middle, and underline () can be used.

  4. Punctuation cannot be used.         

5. You cannot use keywords in bash (you can use the help command to view reserved keywords)

1.1 type of variable

1. Local variables
         Local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables.

2. Environmental variables
         All programs, including those started by the shell, can access environment variables. Some programs need environment variables to ensure their normal operation.

3.Shell variables
        Shell variables are special variables set by the shell program. Some shell variables are environment variables and some are local variables

# Declaration of variables
name="zhangsan"
for file in `ls /etc`  # Note that this is not a quotation mark
# Or for file in $(ls /etc)
# Call of variable
echo $name
echo ${name}

for skill in Ada Coffe Action Java; do
        echo "I am good at ${skill}Script"
done    

# read-only variable 
url="https://www.baidu.com"
readonly url
url="https://www.baidu.com"

# Delete variable
unset name

2, String

String is the most commonly used and useful data type in shell programming. String can use single quotation marks, double quotation marks or no quotation marks.

Single quotation mark
        Any character in the single quotation mark will be output as is, and the variable in the single quotation mark string is invalid;
        Single quotation marks cannot appear in a single quotation mark string, but can appear in pairs as string splicing.

Double quotation mark
        You can have variables in double quotes
        Escape characters can appear in double quotation marks

# String splicing -- inside double quotation marks, quotation marks are not required for variables with curly braces
root@SYZM:~# name='pengyuyan'
root@SYZM:~# name1="hello,"$name"!"
root@SYZM:~# name2="hello,${name}!"
root@SYZM:~# echo $name1
hello,pengyuyan!
root@SYZM:~# echo $name2
hello,pengyuyan!

# String splicing -- inside single quotation marks, curly braces inside single quotation marks are invalid
root@SYZM:~# passwd='123456'
root@SYZM:~# passwd1='hello,'$passwd'!'  # Single quotes match the nearest single quote
root@SYZM:~# passwd2='hello,${passwd}!'
root@SYZM:~# echo $passwd1
hello,123456!
root@SYZM:~# echo $passwd2
hello,${passwd}!


# Length of string
root@SYZM:~# email="123456@qq.com"  
root@SYZM:~# echo ${#email}  # Total print length
13
root@SYZM:~# echo ${email:1:4}  # Print subscripts 1 through 4, including 4
2345

Within double quotation marks, strings can be spliced. If they are single quotation marks, variables cannot be escaped:

root@SYZM:~# str1='hu ge'
root@SYZM:~# echo "$str1 is handsome"
hu ge is handsome
root@SYZM:~# echo '$str1 is handsome'
$str1 is handsome

  3, Array

bash supports one-dimensional arrays (multi-dimensional arrays are not supported) and does not limit the size of the array.

The subscripts of array elements are numbered from 0. To obtain the elements in the array, the subscript can be an integer or arithmetic expression, and its value should be greater than or equal to 0.

# Define array parentheses to represent the array, and the array elements are separated by space symbols
root@SYZM:~# favs = ("football", "Basketball", "table tennis", "bowling")
root@SYZM:~# favs=${favs[1]}
root@SYZM:~# echo $favs
 Basketball

# @Both * and * can output all the values in the array
root@SYZM:~# echo ${favs[@]}
Basketball table tennis Bowling

# The length of the array, in#take
root@SYZM:~# length1=${#favs[@]}
root@SYZM:~# length2=${#favs[*]}
root@SYZM:~# echo $length1
4
root@SYZM:~# echo $length2
4

4, Notes

Line comment:#

Block comment: < < start character content end character; For example: < < e annotation content e

5, Operator

5.1 arithmetic operators

         The expr keyword is used to perform the operation. The expression must be inside the ` ` symbol. A backslash should be added in front of the multiplication sign to escape \ *. Like other languages, spaces should be added between the added variables for output

a=10
b=20

# 
val=`expr $a + $b`
echo "a + b : $val"

5.2 relational operators

operatorexplaingive an example
-eqCheck whether two numbers are equal, and return true if they are equal.[$a -eq $b] return   false.
-neCheck whether the two numbers are not equal, and return true if they are not equal.[$a -ne $b] returns true.
-gtCheck whether the number on the left is greater than that on the right. If so, return true.[$a -gt $b] returns false.
-ltCheck whether the number on the left is less than that on the right. If so, return true.[$a -lt $b] returns true.
-geCheck whether the number on the left is greater than or equal to that on the right. If so, return true.[$a -ge $b] returns false.
-leCheck whether the number on the left is less than or equal to that on the right. If so, return true.[$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
if [ $a -ne $b ]
then
   echo "$a -ne $b: a Not equal to b"
else
   echo "$a -ne $b : a be equal to b"
fi
if [ $a -gt $b ]
then
   echo "$a -gt $b: a greater than b"
else
   echo "$a -gt $b: a Not greater than b"
fi
if [ $a -lt $b ]
then
   echo "$a -lt $b: a less than b"
else
   echo "$a -lt $b: a Not less than b"
fi
if [ $a -ge $b ]
then
   echo "$a -ge $b: a Greater than or equal to b"
else
   echo "$a -ge $b: a less than b"
fi
if [ $a -le $b ]
then
   echo "$a -le $b: a Less than or equal to b"
else
   echo "$a -le $b: a greater than b"
fi

5.3 Boolean operators

operatorexplaingive an example
!If the expression is true, it returns false; otherwise, it returns true.[! false] returns true.
-oOr operation. If an expression is true, it returns true.[$a -lt 20 -o $b -gt 100] return   true.
-aAnd operation, both expressions return true only when they are true.[$a -lt 20 -a $b -gt 100] return   false.

  5.4 logical operators

operatorexplaingive an example
&&Logical AND[[$a - LT 100 & & $B - GT 100]] returns false
||Logical OR[[$a - LT 100 | $B - GT 100]] returns true
#! /bin/bash
a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

5.5 string operators

operatorexplaingive an example
=Check whether two strings are equal, and return true if they are equal.[$a = $b] returns false.
!=Detect whether two strings are not equal, and return true if they are not equal.[$a! = $b] return   true.
-zCheck whether the string length is 0, and return true if it is 0.[- z $a] returns false.
-nCheck whether the string length is not 0, and return true if it is not 0.[- n "$a"] returns true.
$Check whether the string is empty. If not, return true.[$a] return   true.
#! /bin/bash
a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a be equal to b"
else
   echo "$a = $b: a Not equal to b"
fi
if [ $a != $b ]
then
   echo "$a != $b : a Not equal to b"
else
   echo "$a != $b: a be equal to b"
fi
if [ -z $a ]
then
   echo "-z $a : The string length is 0"
else
   echo "-z $a : String length is not 0"
fi
if [ -n "$a" ]
then
   echo "-n $a : String length is not 0"
else
   echo "-n $a : The string length is 0"
fi
if [ $a ]
then
   echo "$a : String is not empty"
else
   echo "$a : The string is empty"
fi

5.6 document test operator

Operatorexplaingive an example
-b fileCheck whether the file is a block device file. If so, return true.[- b $file] returns false.
-c fileCheck whether the file is a character device file. If so, return true.[- c $file] return   false.
-d fileCheck whether the file is a directory. If so, return true.[- d $file] returns false.
-f fileCheck whether the file is an ordinary file (neither a directory nor a device file). If so, return true.[- f $file] return   true.
-g fileCheck whether the SGID bit is set in the file. If so, return true.[- g $file] return   false.
-k fileCheck whether the file has a sticky bit set. If so, return true.[- k $file] return   false.
-p fileCheck whether the file is a famous pipeline. If so, return true.[- p $file] return   false.
-u fileCheck whether the SUID bit is set in the file. If so, return true.[- u $file] return   false.
-r fileCheck whether the file is readable. If so, return true.[- r $file] return   true.
-w fileCheck whether the file is writable. If so, return true.[- w $file] return   true.
-x fileCheck whether the file is executable. If so, return true.[- x $file] return   true.
-s fileCheck whether the file is empty (whether the file size is greater than 0). If it is not empty, return true.[- s $file] return   true.
-e fileCheck whether files (including directories) exist. If so, return true.[- e $file] return   true.
#! /bin/bash
file="/var/www/runoob/test.sh"
if [ -r $file ]
then
   echo "File readable"
else
   echo "File unreadable"
fi
if [ -w $file ]
then
   echo "File writable"
else
   echo "The file is not writable"
fi
if [ -x $file ]
then
   echo "File executable"
else
   echo "The file is not executable"
fi
if [ -f $file ]
then
   echo "The file is a normal file"
else
   echo "The file is a special file"
fi
if [ -d $file ]
then
   echo "The file is a directory"
else
   echo "File is not a directory"
fi
if [ -s $file ]
then
   echo "File is not empty"
else
   echo "The file is empty"
fi
if [ -e $file ]
then
   echo "File exists"
else
   echo "file does not exist"
fi

6, echo print data

# Normal output
root@SYZM:~# echo "hello world"
hello world

# Show escape characters
root@SYZM:~# echo "\"hello world"\"
"hello world"

# Display variables
root@SYZM:~# name="hu ge"
root@SYZM:~# echo "$name HelloWorld"
hu ge HelloWorld

# Show wrap
root@SYZM:~# echo -e "OK! \n"
OK! 

root@SYZM:~#

# Do not show line breaks
root@SYZM:~# echo -e "OK! \c"
OK!

# Write and overwrite files
root@SYZM:~# echo "hellohandsome" > myfile

# Output variables as is
root@SYZM:~# echo '$name\"'
$name\"

# Execute system commands
root@SYZM:~# echo `date`
Wed 29 Sep 2021 02:08:28 PM CST

7, test command

It is similar to the if command, except that the brackets are changed to variables

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

8, shell control process

8.1 if statement

root@SYZM:~# a=10
root@SYZM:~# b=20
root@SYZM:~# if [ $a == $b ]
> then
> echo "a be equal to b"
> elif [ $a -gt $b ]
> then
> echo "a greater than b"
> elif [ $a -lt $b ]
> then
> echo "a less than b"
> else
> echo "No conditions met!"
> fi  # End flag 
a less than b

8.2 case statement

Select a statement for multiple. You can use a case statement to match a value with a pattern. If the match is successful, execute the matching command.

#! /bin/bash
echo 'Enter a number between 1 and 2:'
echo 'The number you entered is:'
read num  # Similar to input
case $num in
        1) echo 'You chose 1'
        ;;  # Equivalent to break
        2) echo 'You chose 2'
        ;;
        *) echo 'You did not enter a number between 1 and 4'
        ;;
esac  # Equivalent to default

  Operation results:

root@SYZM:~/shell# sh case.sh 
Enter a number between 1 and 2:
The number you entered is:
1
 You chose 1
root@SYZM:~/shell# sh case.sh 
Enter a number between 1 and 2:
The number you entered is:
3
 You did not enter a number between 1 and 4

9, Circulation

9.1 for loop

root@SYZM:~/shell# for loop in 1 2 3 4 5
> do
> echo "The value is: $loop"
> done
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
root@SYZM:~/shell# for str in 'a string','huge hu'
> do
> echo $str
> done
a string,huge hu
root@SYZM:~/shell# 

9.2 while loop

root@SYZM:~/shell# i=1
root@SYZM:~/shell# while(( $i<=5  )); do echo $i; let "i++"; done
1
2
3
4
5

10, break and continue

There are also break and continue in the shell, which is similar to python

# break jumps out of the entire loop
root@SYZM:~# while :
> do
> echo -n "Enter a number between 1 and 5:"
> read aNum
> case $aNum in
> 1|2|3|4|5) echo "The number you entered is $aNum!"
> ;;
> *) echo "The number you entered is not between 1 and 5! game over"
> break
> ;;
> esac
> done
 Enter a number between 1 and 5:3
 The number you entered is 3!
Enter a number between 1 and 5:6
 The number you entered is not between 1 and 5! game over


# continue jumps out of the current loop
root@SYZM:~# while :; do echo -n "enter a number between 1 and 5:"; read aNum; case $aNum in 1|2|3|4|5) echo "the number you entered is $anum!"; *) Echo "the number you entered is not between 1 and 5!"; continue; echo "game over";; esac; done
 Enter a number between 1 and 5:1
 The number you entered is 1!
Enter a number between 1 and 5:6
 The number you entered is not between 1 and 5!
Enter a number between 1 and 5:

11, Functions

linux shell can user-defined functions, which can be called freely in shell scripts. python is similar to it

It can be defined with function fun() or directly with fun() without any parameters.

Parameter returns, plus can be displayed: return returns. If not, the result of the last command will be used as the return value. Return followed by the value n(0-255)

#! /bin/bash
funWithReturn(){
    echo "This function adds the two input numbers..."
    echo "Enter the first number: "
    read aNum
    echo "Enter the second number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of the two numbers entered is $? !"

Posted by Quest on Wed, 29 Sep 2021 15:42:31 -0700