MST
星途 面试题库

面试题:Bash中tee命令在复杂脚本场景下的应用

编写一个Bash脚本,脚本接受一个目录路径作为参数。在该目录下查找所有文本文件(可通过文件扩展名判断),然后对每个文本文件的内容使用tee命令,将其内容输出到标准输出的同时,保存到该文件所在目录下以'.bak'为后缀的备份文件中,并且要求在处理过程中显示当前处理的文件名。请写出完整的脚本代码。
21.8万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Usage: $0 <directory_path>"
    exit 1
fi

directory=$1

if [ ! -d "$directory" ]; then
    echo "The specified path is not a directory."
    exit 1
fi

for file in $directory/*.txt; do
    if [ -f "$file" ]; then
        echo "Processing file: $file"
        tee ${file%.txt}.bak < $file
    fi
done