Shell programming (Chinese_common commands)

1. expr command

exprThe command is used to evaluate the value of the expression, the format is:

expr 表达式

Explanation of expressions:

  • Separate each item with a space
  • Use backslashes in front of shell-specific characters (you can try escaping when you find that the expression is running incorrectly)
  • Enclose strings containing spaces and other special characters in quotes
  • expr will stdout(标准输出)output the result in . If it is a logical relational expression, the result is true and stdout is 1, otherwise it is 0.
  • The exit code of expr: If it is a logical relational expression, the result is true, and the exit code is 0, otherwise it is 1.

string expression

  • length STRING Returns the length of STRING
  • index STRING CHARSET
    The first character position of any single character in CHARSET in STRING, and the subscript starts from 1. Returns 0 if none of the characters in CHARSET exist in STRING.
  • substr STRING POSITION LENGTH
    Returns the substring starting from POSITION and up to LENGTH in the STRING string. Returns an empty string if POSITION or LENGTH is negative, 0 or non-numeric.

举例:

str="Hello World!"

echo `expr length "$str"`  # ``不是单引号,表示执行该命令,输出12
echo `expr index "$str" aWd`  # 输出7,下标从1开始
echo `expr substr "$str" 2 3`  # 输出 ell

integer expression

expr supports ordinary arithmetic operations, and the priority of arithmetic expressions is lower than that of string expressions and higher than that of logical relational expressions.

  • - +
    Addition and subtraction. The parameters at both ends will be converted to integers, and an error will be reported if the conversion fails.
  • / * %
    Division, multiplication, and modulo operations. The parameters at both ends will be converted to integers, and an error will be reported if the conversion fails.

()This table priority can be used, but needs to be escaped with a backslash

Example:

a=3
b=4

echo `expr $a + $b`  # 输出7
echo `expr $a - $b`  # 输出-1
echo `expr $a \* $b`  # 输出12,*需要转义
echo `expr $a / $b`  # 输出0,整除
echo `expr $a % $b` # 输出3
echo `expr \( $a + 1 \) \* \( $b + 1 \)`  # 输出20,值为(a + 1) * (b + 1)

logical relational expression

  • |
    If the first parameter is non-empty and non-zero, return the value of the first parameter, otherwise return the value of the second parameter, but require the value of the second parameter to be non-null or non-zero, otherwise return 0. If the first parameter is non-null or non-zero, the second parameter will not be evaluated.
  • &
    If both arguments are non-null and non-zero, returns the first argument, otherwise returns 0. If the first argument is 0 or empty, the second argument will not be evaluated.
  • < <= = == != >= >
    Compares the arguments at both ends and returns 1 if true, 0 otherwise. "==" is a synonym for "=". "expr" first tries to convert the arguments at both ends into integers, and do arithmetic comparison, if the conversion fails, then do character comparison according to the character set collation.
  • () This table priority can be used, but needs to be escaped with a backslash

Example:

a=3
b=4

echo `expr $a \> $b`  # 输出0,>需要转义
echo `expr $a '<' $b`  # 输出1,也可以将特殊字符用引号引起来
echo `expr $a '>=' $b`  # 输出0
echo `expr $a \<\= $b`  # 输出1

c=0
d=5

echo `expr $c \& $d`  # 输出0
echo `expr $a \& $b`  # 输出3
echo `expr $c \| $d`  # 输出5
echo `expr $a \| $b`  # 输出3

2. read command

readcommand is used to read a single line of data from standard input. The exit code is 1 when the end-of-file is read, otherwise 0.

Parameter Description

  • -p: You can receive prompt information later
  • -t: Followed by the number of seconds, define the waiting time for input characters, and this command will be ignored automatically after the waiting time is exceeded

example

acs@9e0ebfcd82d7:~$ read name  # 读入name的值
acwing yxc  # 标准输入

acs@9e0ebfcd82d7:~$ echo $name  # 输出name的值
acwing yxc  #标准输出

acs@9e0ebfcd82d7:~$ read -p "Please input your name: " -t 30 name  # 读入name的值,等待时间30秒
Please input your name: acwing yxc  # 标准输入

acs@9e0ebfcd82d7:~$ echo $name  # 输出name的值
acwing yxc  # 标准输出

3.echo command

echo will wrap by default

echofor outputting strings. Command format:

echo STRING

show normal string

echo "Hello AC Terminal"
echo Hello AC Terminal  # 引号可以省略

show escape characters

echo "\"Hello AC Terminal\""  # 注意只能使用双引号,如果使用单引号,则不转义
echo \"Hello AC Terminal\"  # 也可以省略双引号

display variable

name=yxc
echo "My name is $name"  # 输出 My name is yxc

show newline

echo -e "Hi\n"  # -e 开启转义
echo "acwing"

输出结果:

Hi

acwing

display without line break

echo -e "Hi \c" # -e 开启转义 \c 不换行
echo "acwing"

输出结果:

Hi acwing

Show results directed to file

echo "Hello World" > output.txt  # 将内容以覆盖的方式输出到output.txt中

Output the string as it is, without escaping or taking variables (using single quotes)

name=acwing
echo '$name\"'

输出结果

$name\"

Display the execution result of the command

echo `date`

输出结果:

Wed Sep 1 11:45:33 CST 2021

4. printf command

printfprintfCommands are used to format output, similar to functions in C/C++ .

By default no newline will be appended to the end of the string

Command format:

printf format-string [arguments...]

usage example

脚本内容

printf "%10d.\n" 123  # 占10位,右对齐
printf "%-10.2f.\n" 123.123321  # 占10位,保留2位小数,左对齐
printf "My name is %s\n" "yxc"  # 格式化输出字符串
printf "%d * %d = %d\n"  2 3 `expr 2 \* 3` # 表达式的值作为参数

输出结果

       123.
123.12    .
My name is yxc
2 * 3 = 6

5.test command and judgment symbol []

Logical operators && and ||

  • &&means with, || means or
  • The two have a short-circuit principle: expr1 && expr2: When expr1it is false, ignore it directly expr2
    expr1 || expr2: When expr1 is true, ignore expr2 directly
  • The exit code of the expression is 0, which means true; if it is non-zero, it means false. (as opposed to the definition in C/C++)

test command

Enter man test on the command line to view the usage of the test command.

  • testCommands are used to determine the file type and compare variables.
  • testCommands exit codereturn results instead of using stdout. 0 means true, non-zero means false.

For example:

test 2 -lt 3  # 为真,返回值为0
echo $?  # 输出上个命令的返回值,输出0
acs@9e0ebfcd82d7:~$ ls  # 列出当前目录下的所有文件
homework  output.txt  test.sh  tmp
acs@9e0ebfcd82d7:~$ test -e test.sh && echo "exist" || echo "Not exist"
exist  # test.sh 文件存在
acs@9e0ebfcd82d7:~$ test -e test2.sh && echo "exist" || echo "Not exist"
Not exist  # testh2.sh 文件不存在

file type judgment

Command format:

test -e filename  # 判断文件是否存在
Test parameters representative meaning
-e Does the file exist
-f Is it a file
-d Is it a directory

File Permission Judgment

Command format:

test -r filename  # 判断文件是否可读
More operational test parameters representative meaning
-r whether the file is readable
-w whether the file is writable
-x Is the file executable
-s Is it a non-empty file

comparison between integers

​ Command format:

test $a -eq $b  # a是否等于b
Test parameters representative meaning
-eq is a equal to b
-ne Is a not equal to b
-gt Is a greater than b
-lt Is a less than b
-ge Is a greater than or equal to b
-le whether a is less than or equal to b

string comparison

Test parameters representative meaning
test -z STRING Determine whether STRING is empty, if it is empty, return true
test -n STRING Determine whether STRING is not empty, if not, return true (-n can be omitted)
test str1 == str2 Determine whether str1 is equal to str2
test str1 != str2 Determine whether str1 is not equal to str2

multiple condition judgment

Command format:

test -r filename -a -x filename
Test parameters representative meaning
-a Are the two conditions simultaneously true?
-o Whether at least one of the two conditions holds
! Negate. Such as test! -x file, when the file is not executable, return true

judgment symbol[]

[]Almost exactly the same as testusage, more commonly used in if statements. In addition [[]], it is []an enhanced version that supports more features.

For example:

[ 2 -lt 3 ]  # 为真,返回值为0 注意:两边必须有空格
echo $?  # 输出上个命令的返回值,输出0
acs@9e0ebfcd82d7:~$ ls  # 列出当前目录下的所有文件
homework  output.txt  test.sh  tmp

acs@9e0ebfcd82d7:~$ [ -e test.sh ] && echo "exist" || echo "Not exist"
exist  # test.sh 文件存在

acs@9e0ebfcd82d7:~$ [ -e test2.sh ] && echo "exist" || echo "Not exist"
Not exist  # testh2.sh 文件不存在

Notice:

  • []Each item must be separated by a space
  • Variables enclosed in square brackets,最好用双引号括起来
  • Constants in square brackets, preferably enclosed in single or double quotes

For example:

name="acwing yxc"
[ $name == "acwing yxc" ]  # 错误,等价于 [ acwing yxc == "acwing yxc" ],参数太多
[ "$name" == "acwing yxc" ]  # 正确

Supongo que te gusta

Origin blog.csdn.net/qq_46312987/article/details/125047946
Recomendado
Clasificación