MST
星途 面试题库

面试题:Bash脚本中的循环与文件处理

编写一个Bash脚本,遍历指定目录下的所有文件,将文件名中包含特定字符串(如'example')的文件移动到另一个指定目录。要求处理过程中对可能出现的权限问题给出适当提示。
27.5万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查是否提供了足够的参数
if [ $# -ne 3 ]; then
    echo "Usage: $0 <source_directory> <target_directory> <specific_string>"
    exit 1
fi

source_dir=$1
target_dir=$2
specific_str=$3

# 检查目标目录是否存在
if [ ! -d "$target_dir" ]; then
    echo "目标目录 $target_dir 不存在,正在创建..."
    mkdir -p "$target_dir"
    if [ $? -ne 0 ]; then
        echo "创建目标目录失败,请检查权限。"
        exit 1
    fi
fi

# 遍历源目录下的所有文件
for file in "$source_dir"/*; do
    if [ -f "$file" ]; then
        # 检查文件名是否包含特定字符串
        if [[ "$file" == *"$specific_str"* ]]; then
            # 尝试移动文件
            mv "$file" "$target_dir"
            if [ $? -eq 0 ]; then
                echo "成功移动文件 $file 到 $target_dir"
            else
                echo "移动文件 $file 失败,请检查权限。"
            fi
        fi
    fi
done