n03t0n / hdu-experiments

用来讨论linux
0 stars 0 forks source link

刘桑的issue #2

Open n03t0n opened 3 weeks ago

n03t0n commented 3 weeks ago

图片

n03t0n commented 3 weeks ago

抽了个1 2 7题

n03t0n commented 3 weeks ago

第七题

#!/bin/bash

# 获取字符串长度
get_length() {
    echo ${#1}
}

# 提示用户输入至少5个字符串
echo "请输入至少5个字符串,每输入一个按回车:"

# 读入字符串到数组
strings=()
while IFS= read -r line; do
    strings+=("$line")
    if [ ${#strings[@]} -ge 5 ]; then
        read -p "是否继续输入更多字符串?(y/n): " choice
        [[ $choice =~ ^[nN]$ ]] && break
    fi
done

# 检查输入的字符串数量是否不少于5个
if [ ${#strings[@]} -lt 5 ]; then
    echo "输入的字符串数量少于5个,退出脚本。"
    exit 1
fi

# 获取第一个字符串的长度作为参考
first_length=$(get_length "${strings[0]}")

# 检查是否所有字符串长度都相同
all_same_length=true
for str in "${strings[@]}"; do
    if [ $(get_length "$str") -ne $first_length ]; then
        all_same_length=false
        break
    fi
done

# 输出结果
if $all_same_length; then
    echo "所有输入的字符串长度相同,长度为:$first_length"
else
    echo "输入的字符串长度各不相同,具体长度如下:"
    for i in "${!strings[@]}"; do
        echo "字符串:'${strings[$i]}' 长度:$(get_length "${strings[$i]}")"
    done
    echo "比较完成。"
fi
n03t0n commented 3 weeks ago

第2题

#!/bin/bash

# 输出文件名
OUTPUT_FILE="account_info.txt"

# 获取账户信息
ACCOUNT_INFO=$(cat /etc/passwd)

# 统计账户数量
ACCOUNT_COUNT=$(wc -l /etc/passwd | awk '{print $1}')

# 输出账户信息和数量到文件
echo "账户信息:" > $OUTPUT_FILE
echo "$ACCOUNT_INFO" >> $OUTPUT_FILE
echo -e "\n账户数量:$ACCOUNT_COUNT" >> $OUTPUT_FILE

# 显示结果
echo "账户信息和数量已经输出到 $OUTPUT_FILE"
n03t0n commented 3 weeks ago

第1题

#!/bin/bash

# 个人工作路径
WORK_PATH="/home/liuyunqi/Desktop/final_test/1"

# 检查WORK_PATH是否存在
if [ ! -d "$WORK_PATH" ]; then
  echo "工作路径不存在:$WORK_PATH"
  exit 1
fi

# 统计/etc/目录下的文件夹和文件
DIR_COUNT=$(find /etc -mindepth 1 -maxdepth 1 -type d | wc -l)
FILE_COUNT=$(find /etc -mindepth 1 -maxdepth 1 -type f | wc -l)

# 获取文件夹名称
DIR_NAMES=$(find /etc -mindepth 1 -maxdepth 1 -type d -printf "%f\n")
# 获取文件名称
FILE_NAMES=$(find /etc -mindepth 1 -maxdepth 1 -type f -printf "%f\n")

# 输出到plan.d文件
echo "文件夹数量: $DIR_COUNT" > "$WORK_PATH/plan.d"
echo "$DIR_NAMES" >> "$WORK_PATH/plan.d"

# 输出到plan.f文件
echo "文件数量: $FILE_COUNT" > "$WORK_PATH/plan.f"
echo "$FILE_NAMES" >> "$WORK_PATH/plan.f"
*/20 21-23 * * * /home/liuyunqi/Desktop/final_test/1/list_etc_files.sh
*/20 0-9 * * * /home/liuyunqi/Desktop/final_test/1/list_etc_files.sh