面试题答案
一键面试Bash脚本
#!/bin/bash
input_file="$1"
output_file="$2"
> "$output_file" # 清空输出文件
while read -r path; do
if [ -d "$path" ]; then
file_count=$(ls -1 "$path" | wc -l)
echo "$path: $file_count" >> "$output_file"
fi
done < "$input_file"
Bats测试用例
首先安装bats
,在Debian或Ubuntu系统上可以使用sudo apt install bats
安装。
创建测试文件test_script.bats
:
#!/usr/bin/env bats
setup() {
# 创建临时输入文件和输出文件
input_file=$(mktemp)
output_file=$(mktemp)
# 创建测试目录和文件
mkdir -p test_dir
touch test_dir/file1 test_dir/file2
echo "test_dir" > "$input_file"
}
teardown() {
# 删除临时文件和目录
rm -f "$input_file" "$output_file"
rm -rf test_dir
}
@test "目录存在且文件统计正确" {
run bash your_script.sh "$input_file" "$output_file"
expected="test_dir: 2"
grep -q "$expected" "$output_file"
[ "$status" -eq 0 ]
}
@test "非目录路径处理" {
echo "not_a_dir" >> "$input_file"
run bash your_script.sh "$input_file" "$output_file"
refute grep -q "not_a_dir" "$output_file"
[ "$status" -eq 0 ]
}
注意将上述your_script.sh
替换为实际脚本文件名。运行测试时执行bats test_script.bats
。