Linux shell syntax - common commands

Tools and Resource Center

Help developers work more efficiently and provide tools and resources around the whole life cycle of developers
developer.aliyun.com/tool?spm=a1z3...

This paper introduces the following contents: expr, read, echo, printf, test command and judgment symbol []

expr command

The expr command is used to evaluate the value of an expression. The format is: expr expression

Expression usage:

  • Separate each item with a space
  • Place a backslash before a shell specific character (that is, escape)
  • Strings containing spaces and other special characters should be enclosed in quotation marks
  • expr will output the result in stdout. If it is a logical relationship expression, the result is true, stdout is 1, otherwise it is 0
  • expr also has an exit code. If it is a logical relationship expression and the result is true, the exit code is 0, otherwise it is 1

String expression

  • length STRING: returns the length of a STRING
  • index STRING CHARSET: returns the first character position of any single character in CHARSET in the STRING, and the subscript starts from 1. If there is no character in CHARSET in STRING, 0 is returned.
  • substr STRING POSITION LENGTH: returns the STRING with the maximum LENGTH of LENGTH starting from POSITION in the STRING string. Returns an empty STRING if POSITION or LENGTH is negative, 0, or non numeric.

Example:

str="Hello World!"

echo `expr length "$str"` # Note that ` ` is not a single quotation mark, which means to obtain stdout of command in ` ` and output 12
echo `expr index "$str" aWd` #Output 7, subscript from 1
echo `expr substr "$str" 2 3` #Output ell

Integer expression

expr supports ordinary arithmetic operations. Arithmetic expressions have lower priority than string expressions and higher priority than logical relationship expressions.

  • +-: addition and subtraction. The parameters at both ends will be converted to integers. If the conversion fails, an error will be reported.
  • */%: multiplication and division modulo operation. The parameters at both ends will be converted to integers. If the conversion fails, an error will be reported.
  • (): can indicate priority, but need backslash escape

Example:

a=3
b=4

echo `expr $a + $b`  # Output 7
echo `expr $a - $b`  # Output - 1
echo `expr $a \* $b`  # Output 12, * needs escape
echo `expr $a / $b`  # Output 0, integer division
echo `expr $a % $b` # Output 3
echo `expr \( $a + 1 \) \* \( $b + 1 \)`  # Output 20, value is (a + 1) * (b + 1)

Logical relation expression

  • |: if the first parameter is non null and non-0, the value of the first parameter will be returned; otherwise, the value of the second parameter will be returned. However, the value of the second parameter is required to be non null or non-0, otherwise, 0 will be returned. If the first parameter is non null or non-zero, the second parameter is not evaluated.
  • &: if both parameters are non null and non-0, the first parameter is returned; otherwise, 0 is returned. If the first parameter is 0 or empty, the second parameter is not evaluated.
  • < <= = == != >= > : Compare the parameters at both ends. If it is true, it returns 1, otherwise it returns 0. "=" Is a synonym for "=" expr "first try to convert the parameters at both ends into integers and make arithmetic comparison. If the conversion fails, make character comparison according to the sorting rules of the character set.
  • (): the priority of this table can be, but it needs to be escaped with a backslash

Example:

a=3
b=4

echo `expr $a \> $b`  # Output 0, > needs escape
echo `expr $a '<' $b`  # Output 1, or enclose special characters in quotation marks
echo `expr $a '>=' $b`  # Output 0
echo `expr $a \<\= $b`  # Output 1

c=0
d=5

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

read command

The read command is used to read the current line of data from standard input (stdin). When the end of the file (ctrl+d) is read, the exit code is 1, otherwise it is 0.

Optional parameters:

  • -p: The prompt information to be output can be followed
  • -t: It is followed by a number in seconds to define the waiting time for accepting input. This command will be ignored automatically when it times out

Example:

read name # Read in the value of name
ubuntu # stdin
echo $name # Output the value of name

read -p "Please input your name:" -t 30 name # Read the value of name and wait for 30 seconds

echo command

The echo command is used to output a string in the format echo STRING

Display normal string

echo "hello ubuntu"
echo hello ubuntu # Quotation marks can be omitted

Show escape characters

-The e parameter indicates escape. This parameter must be added to some escape characters to work. For example: \ \ a \b \c \d \e \f \n \r \t \v, other escape characters may be escaped without - E

echo "\"hello ubuntu\"" # Using double quotation marks will escape
echo \"hello ubuntu\" # You can also escape without using double quotation marks

# If there is no escape, the parameter - e can be added
echo -e "Hi\n" # -e open escape
echo "ubuntu"

:<<!
The output of the fifth and sixth lines is as follows:
Hi

ubuntu
!

Display variables

name=ubuntu
echo "hi,$name" # Output hi,ubuntu

Show no line breaks

echo -e "hi \c" # \c means no line break
echo "ubuntu"

The output result is: hi ubuntu

Redirect results to file

echo "hello ubuntu" > output.txt # Output the display results to output.com in overlay mode Txt

Output the string as it is without escaping or fetching variables

name=ubuntu
echo '$name\"'

The output result is: $name\“

Displays the execution result of the command (stdout)

echo `date`

The output result is: 19:05:20 CST on Sunday, September 5, 2021

printf command

The printf command is used to format the output, similar to the printf function in C/C + +. By default, line breaks are not added at the end of the string.

Format: printf format string [arguments...]

Example:

Script content:

printf "%10d.\n" 123  # 10 places, right aligned
printf "%-10.2f.\n" 123.123321  # 10 digits, 2 decimal places reserved, left aligned
printf "My name is %s\n" "ubuntu"  # Format output string
printf "%d * %d = %d\n"  2 3 `expr 2 \* 3` # The value of the expression as an argument

Output results:

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

Logical operators & & and||

  • &&Means and, | means or

  • Similar to the logical operation in the expr command, these two logical operators also have the short circuit principle:

    Expr1 & & expr2: skip the operation of expr2 when expr1 is false

    Expr1 | expr2: skip the operation of expr2 when expr1 is true

  • When the exit code of the expression is 0, it means true, and non-zero means false

test command

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

The test command returns the result with exit code instead of stdout. 0 means true and non-zero means false.

The test command and logical operation match to make a simple condition judgment, for example:

test -e test.sh && echo "exist" || echo "not exist"
# Used to judge the file test If sh exists, output exist; otherwise, output not exist

File type judgment

test -e filename # Determine whether the file exists
test -f filename # Judge whether it is an ordinary file
test -d filename # Determine whether it is a directory

File permission judgment

test -r filename # Determine whether the file is readable
test -w filename # Judge whether the file is writable
test -x filename # Determine whether the file is executable
test -s filename # Judge whether the file is not empty

Comparison between integers

test $a -eq $b # Is a equal to b
test $a -ne $b # Is a not equal to b
test $a -gt $b # Is a greater than b
test $a -lt $b # Is a less than b
test $a -ge $b # Is a greater than or equal to b
test $a -le $b # Is a less than or equal to b

string comparison

test -z STRING # Judge whether the STRING is empty. If yes, it returns true
test -n STRING # Judge whether the STRING is non empty. If yes, it returns 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 conditional decision

test -r filename -a -x filename 
  • -a: Are the two conditions valid at the same time
  • -o: Is at least one of the two conditions true
  • !: Reverse. Such as test- X file returns true when file is not executable

Judgment symbol []

[] is almost as like as two peas in test, often used in if statements, and also [[]], which can be considered as a enhanced version to support more features.

[ 2 -lt 3 ] # Similarly, the return value is 0, indicating true. Note that there is a space after [and before], otherwise an error will be reported

Similar to test, [] can also be used with logical operation to make simple conditional judgment

[ -e test.sh ] && echo "exist" || echo "not exist"

It should be noted that:

  • Each item in [] should be separated by a space
  • Constants and variables in [] should be enclosed in double quotation marks, otherwise errors may be reported due to spaces in constants and variables

This article is transferred from: developer.aliyun.com/article/78968...

Added by yarub on Wed, 15 Dec 2021 15:38:33 +0200