shell scripting

Practice questions:

Insert image description here

1. Write a function to print green 0K and red FAILED, and determine whether there is a parameter. If it exists, it will be 0k, and if it does not exist, it will be FAILED.

#!/bin/bash

function print_result() {
    
    
    if [ $# -eq 0 ]; then
        echo -e "\033[0;31mFAILED\033[0m"
    else
        echo -e "\033[0;32m0K\033[0m"
    fi
}

# 调用函数测试
print_result
print_result param1

2. Write a function to determine whether there are no positional parameters. If there are no parameters, an error will be prompted.

#!/bin/bash

function check_arg() {
    
    
    if [ $# -eq 0 ]; then
        echo "Error: No arguments provided."
    else
        echo "Arguments provided."
    fi
}

# 调用函数测试
check_arg
check_arg param1

3. Write a function to implement two numbers as parameters and return the maximum value

#!/bin/bash

function max_num() {
    
    
    if [ $1 -gt $2 ]; then
        echo $1
    else
        echo $2
    fi
}

# 调用函数测试
max_num 10 20
max_num 30 20

4. Write a function to implement two integer bit parameters and calculate addition, subtraction, multiplication and division.

#!/bin/bash

function math_operation() {
    
    
    echo "Addition: $(($1 + $2))"
    echo "Subtraction: $(($1 - $2))"
    echo "Multiplication: $(($1 * $2))"
    if [ $2 -eq 0 ]; then
        echo "Cannot divide by 0."
    else
        echo "Division: $(($1 / $2))"
    fi
}

# 调用函数测试
math_operation 10 5
math_operation 20 0

5. Assign each line of the /etc/shadow file as an element to the array

#!/bin/bash

declare -a shadow_arr=() # 声明一个空数组

while read line; do
    shadow_arr+=("$line") # 将每行字符串添加到数组中
done < /etc/shadow

echo "shadow_arr: ${shadow_arr[@]}" # 打印数组元素

6. Use an associative array to count the number of different types of shells used by users in the file /etc/passwd

#!/bin/bash

declare -A shell_counts=() # 声明关联数组

while read line; do
    shell=$(echo $line | awk -F':' '{print $NF}') # 获取shell类型
    ((shell_counts["$shell"]++)) # 关联数组计数
done < /etc/passwd

# 遍历关联数组打印每个类型的数量
for key in "${
     
     !shell_counts[@]}"; do
    echo "$key: ${shell_counts[$key]}"
done

7. Use an associative array to count the number of files in a specified directory by extension

#!/bin/bash

declare -A file_counts=() # 声明关联数组

dir_path="/path/to/dir" # 指定目录路径

for file_path in $dir_path/*; do
    file_name=$(basename "$file_path") # 获取文件名
    extension="${file_name##*.}" # 获取文件扩展名
    ((file_counts["$extension"]++)) # 关联数组计数
done

# 遍历关联数组打印每个扩展名的数量
for key in "${
     
     !file_counts[@]}"; do
    echo "$key: ${file_counts[$key]}"
done

Guess you like

Origin blog.csdn.net/m0_51828898/article/details/129907687