[Shell] Basic Grammar (2)


1. Shell Basic Grammar

file name substitution

The characters used for matching are called wildcards (Wildcard), such as: * ? [ ]the details are as follows:

  • *: matches 0 or more of any character

insert image description here

  • ?: matches any character

insert image description here

  • [ ]: matches one occurrence of any character in the square brackets

insert image description here

The prerequisite for successful replacement is that the file must exist. If the file does not exist, it cannot be replaced.

Parameter expansion:

  • touch {1, 2, 3, 4} / touch{1..4}.txt

insert image description here


command substitution

Execute a certain command and store the content of the standard output of this command in a variable.

varname= cmd arg1 arg2 ...
varname=$(date)

#!/bin/bash 
DateTime=`date`
echo "DateTime is " $DateTime 

insert image description here

Get the path where the current script is located:

#获取当前脚本所在路径 ,在这个路径touch一个1.txt
curPath=$(cd `dirname $0`;pwd)
touch $curPath/1.txt

insert image description here


arithmetic substitution

Do the most basic integer arithmetic

var=45
var2=2
echo $[var+3]
echo $((var+3))
echo $((var*var2))
echo $(($var*$var2))
# 将10以八进制来解析,最后得到的是10进制的8,最后再加11等于19
echo $[8#10+11]

insert image description here


escape character

Similar to the C language, it is used as an escape character\ in the Shell to remove the special meaning of the single character immediately following it (except carriage return), in other words, the character immediately following it takes the literal value. For example:

insert image description here

quotation marks

apostrophe:

Unlike the C language, the single quotes and double quotes in Shell scripts are string delimiters, not character delimiters. Single quotes are used to keep the literal values ​​of all characters within the quotes, even \ and carriage returns inside the quotes, but single quotes cannot appear in the string. If the quotation marks are not matched, press Enter, and the Shell will give a continuation prompt, asking the user to match the quotation marks. For example:

insert image description hereinsert image description here

Double quotes:

Content enclosed in double quotes will be treated as a single string. It prevents wildcard expansion, but allows variable expansion. This is handled differently than single quotes.

insert image description here

Before we use variables, if the variable is passed as a parameter, we should habitually add double quotes to prevent spaces in the variable.


Two, Shell script syntax

condition test

How to express true and false in the shell? Directly use the return status of a certain command to judge whether it is true or false - main函数的返回值 . We know that in the main function, 0 means normal return, and non-zero means abnormal return. It is the opposite of C language.

We can $?get the return status of the previous command through .

insert image description here

Commands for conditional testing: test 表达式 /[ 表达式 ]

  • (EXPRESSION )tests whether the expression is true
  • !EXPRESSION
  • EXPRESSION1 -aEXPRESSION2 logical AND
  • EXPRESSION1 -oEXPRESSION2 logical OR
  • -nSTRING judges that the string is not an empty string
  • -zSTRING judges that the string length is 0
  • STRING1 =STRING2 Determines string equality
  • STRING1 !=STRING2 judges that the strings are not equal
  • INTEGER1 -eqINTEGER2 Judge integer equality
  • INTEGER1 -geINTEGER2 Judgment integer 1>= integer 2
  • INTEGER1 -gtINTEGER2 judge integer 1> integer 2
  • INTEGER1 - leINTEGER2 judge integer 1<= integer 2
  • INTEGER1 -ltINTEGER2 judge integer 1< integer 2
  • INTEGER1 -neINTEGER2 Judgment integer 1 != integer 2
  • FILE1 -ntFILE2 Judging that file 1 is newer than file 2 (refers to the last modification time)
  • FILE1 -otFILE2 Judging that file 1 is older than file 2
  • -bFILE block device
  • -cFILE character device
  • -dFILE judges whether it is a directory
  • -eFILE simply judges whether the file exists
  • -fFILE judges that the file is an ordinary file
  • -hFILE / -L FILE determine if it is a symbolic link
  • -kFILE Determines whether the sticky bit of the file is set
  • -pFILE Determines whether the file is a named pipe
  • -rFILE Determines whether the file has read permission
  • -sFILE judges that the file exists and its size is greater than 0 bytes
  • -SFILE Determines whether the file is a socket file
  • -tFD judges that a file descriptor is opened by the terminal
  • -wFILE determines whether there is write permission
  • -xFILE has execute permission

branch structure

Similar to the C language, use if、then、elif、else、fithese commands to implement branch control in the Shell.

#!/bin/bash
if [ -f /bin/bash ] # 判断bash文件是不是一个普通文件
then 
	echo "/bin/bash is a file"
else 
	echo "/bin/bash is NOT a file"
fi

insert image description here

" :" is a special command called empty command, this command does not do anything, but Exit Status is always true.

#!/bin/bash
if false
then
    : 
else
    echo "always false"
fi

insert image description here

#!/bin/bash
echo "Is it morning? Please answer yes or no!"
#读取用户输入的一个变量
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]
then
    echo "Good morning"
elif [ "$YES_OR_NO" = "no" ] ; then
    echo "Good afternoon"
else
    echo "Not recognized"
    :
fi

insert image description here

In addition, Shell also provides &&和||syntax, which is similar to C language and has Short-circuit features.

Branch structure:

case 表达式 in
val1|pattern1)
    xxxxxx
    ;;
val2|pattern2)
    xxxxxx
    ;;
*)
    xxxx
    ;;
esac     #将case倒着写
#!/bin/bash
echo "Is it morning? Please answer yes or no!"
#读取用户输入的一个变量
read YES_OR_NO

case "$YES_OR_NO" in
yes|y|Yes|YES)
    echo "Good morning"
    ;;
[nN][oO])
    echo "Good afternoon"
    ;;
*)
    echo "Not recognized"
    ;;
esac

insert image description here


cycle

forThe traversal mode of the loop:

for varname in 列表 ; do  #do可以单独写一行,如果写在for这一样就要分号
    .....
    echo $varname
done

控制循环次数
for i in {1..100}
do
    ...
done

遍历目录
for i in `ls`
do
    ....
done
for FRUIT in apple banana pear
do 
  echo "I like $FRUIT"
done

insert image description here

# 计算从1加到100的值,使用for循环
sum=0
for i in {
    
    1..100}
do 
  sum=$[$sum+$i]
done
echo $sum

insert image description here


# 遍历当前目录,看当前目录中的普通文件和目录
for f in `ls`
do 
  if [ -f "$f" ]
  then
    echo "$f 是一个文件"
  elif [ -d "$f" ]
  then  
    echo "$f 是一个目录"
  else 
    echo "Not recognized"
  fi
done

insert image description here

whileloop traversal

while 命令|条件测试
do
    xxxx
done

break 和 continue 跟C中的一样
echo "Please input paswd"
sum=1
read try
while [ "$try" != "secret" ]
do 
  if [ "$sum" -ge 5 ]
  then 
    echo"Error 5 times, exit"
    break
  fi 
  echo "Sorry, try again!"
  read try 
  sum=$[$sum+1]
done

3. Summary

Shell is the glue of command-line tools. No language can combine a large number of command-line tools as easily as Shell. In principle, Shell can do anything, but obviously it is most suitable for automation, because you only need to copy all the commands you typed manually into a file. Well, see you next time!

Guess you like

Origin blog.csdn.net/m0_67595314/article/details/132130470