问题:如何在Shell脚本中接收和处理命令行参数?
解答:
#!/bin/bash
# 使用特殊变量获取参数
echo "脚本名称: $0"
echo "第一个参数: $1"
echo "第二个参数: $2"
echo "所有参数: $@"
echo "参数个数: $#"
# 示例使用
for arg in "$@"; do
echo "参数: $arg"
done
问题:在Shell脚本中如何判断前一个命令是否成功执行?
解答:
#!/bin/bash
command_that_might_fail
if [ $? -eq 0 ]; then
echo "命令执行成功"
else
echo "命令执行失败"
fi
# 更简洁的写法
if command_that_might_fail; then
echo "命令执行成功"
else
echo "命令执行失败"
fi
问题:在Shell脚本中如何正确比较字符串和数字?
解答:
#!/bin/bash
# 字符串比较
str1="hello"
str2="world"
if [ "$str1" = "$str2" ]; then
echo "字符串相等"
else
echo "字符串不相等"
fi
# 数字比较
num1=10
num2=20
if [ $num1 -eq $num2 ]; then
echo "数字相等"
elif [ $num1 -lt $num2 ]; then
echo "num1小于num2"
else
echo "num1大于num2"
fi
问题:如何逐行读取文件内容并进行处理?
解答:
#!/bin/bash
# 方法1: while循环+read
while IFS= read -r line; do
echo "处理行: $line"
done < "filename.txt"
# 方法2: for循环(不推荐处理包含空格的行)
for line in $(cat filename.txt); do
echo "处理行: $line"
done
问题:有哪些调试Shell脚本的方法?
解答:
#!/bin/bash
# 1. 使用-x选项调试
bash -x script.sh
# 2. 在脚本中设置调试模式
set -x # 开启调试
# 你的代码
set +x # 关闭调试
# 3. 使用trap调试
trap 'echo "在行: $LINENO, 变量: $var"' DEBUG
问题:如何检查文件或目录是否存在?
解答:
#!/bin/bash
file="example.txt"
dir="example_dir"
# 检查文件是否存在
if [ -f "$file" ]; then
echo "$file 存在"
else
echo "$file 不存在"
fi
# 检查目录是否存在
if [ -d "$dir" ]; then
echo "$dir 存在"
else
echo "$dir 不存在"
fi
问题:如何在Shell脚本中声明和使用数组?
解答:
#!/bin/bash
# 声明数组
fruits=("Apple" "Banana" "Orange")
# 访问数组元素
echo "第一个水果: ${fruits[0]}"
# 遍历数组
for fruit in "${fruits[@]}"; do
echo "水果: $fruit"
done
# 数组长度
echo "水果数量: ${#fruits[@]}"
# 添加元素
fruits+=("Grape")
问题:如何使用Shell脚本设置定时任务?
解答:
#!/bin/bash
# 1. 使用crontab
# 编辑当前用户的crontab
crontab -e
# 添加如下行每天凌晨3点执行脚本
# 0 3 * * * /path/to/script.sh
# 2. 使用at命令执行一次性任务
echo "/path/to/script.sh" | at 3:00 AM tomorrow
问题:如何在脚本中捕获信号并执行清理操作?
解答:
#!/bin/bash
cleanup() {
echo "执行清理操作..."
rm -f tempfile.txt
exit 1
}
# 捕获SIGINT (Ctrl+C)和SIGTERM
trap cleanup SIGINT SIGTERM
# 主脚本逻辑
echo "脚本运行中..."
touch tempfile.txt
sleep 60
问题:如何在Shell脚本中实现并行执行多个任务?
解答:
#!/bin/bash
# 方法1: 使用后台进程
task1() { sleep 2; echo "任务1完成"; }
task2() { sleep 3; echo "任务2完成"; }
task1 &
task2 &
# 等待所有后台任务完成
wait
# 方法2: 使用GNU parallel(需要安装)
# parallel ::: "command1" "command2" "command3"
echo "所有任务完成"
这些问题和解答涵盖了Shell脚本编程中的常见场景和技巧,适合面试准备和日常开发参考。