Shell script development: practical application of printf and test commands

Table of contents

Shell printf command

print simple text

Shell test command

1. File test

2. String comparison

3. Integer comparison

logic operation:


Shell printf command

When you use the printf command in the shell, it helps you format and output text.

print simple text

This will simply print the string "Hello, World!" with a newline character \n added at the end to break the line.

printf "Hello, World!\n"

Shell test command

When you use the test command in the shell, it is used to test whether the condition is true (True). The test command is usually used for conditional judgment in Shell scripts, so as to perform different operations according to the result of the condition.

1. File test

Attributes for testing files and directories

-e file: Check if the file exists.

-f file: Check if the file is a regular file.

-d file: Check if the file is a directory.

-s file: Check that file is not empty (i.e. file size is greater than zero).

-r file: Check if the file is readable.

-w file: Check if the file is writable.

-x file: Check if the file is executable.

Example:

if [ -e "myfile.txt" ]; then
    echo "文件存在"
fi

2. String comparison

the content of the test string

String1 = String2: Checks if two strings are equal.

String1 != String2: Checks if two strings are not equal.

-n string: Check if the string is not empty.

-z string: Check if the string is empty.

Example:

if [ "$name" = "Alice" ]; then
    echo "姓名是Alice"
fi

3. Integer comparison

for testing integer values

int1 -eq int2: Checks if two integers are equal.

int1 -ne int2: Checks if two integers are not equal.

integer1 -lt integer2: Checks if integer1 is less than integer2.

integer1 -le integer2: Checks if integer1 is less than or equal to integer2.

integer1 -gt integer2: Check if integer1 is greater than integer2.

integer1 -ge integer2: Checks if integer1 is greater than or equal to integer2.

Example:

if [ $age -lt 18 ]; then
    echo "年龄小于18岁"
fi

logic operation:

for logical operations

! Expression: Logical NOT, negation operation.

expression1 -a expression2: Logical AND, returns true when both expressions are true.

expression1 -o expression2: logical or, returns true when at least one of the two expressions is true.

Example:

if [ ! -e "file.txt" -a "$user" = "admin" ]; then
    echo "文件不存在且用户是管理员"
fi

Guess you like

Origin blog.csdn.net/m0_67906358/article/details/132646588