Shell脚本是一组Shell命令的文本文件,用于执行特定的任务。以下是一些常用的Shell脚本类型和示例:
-
Hello World:
#!/bin/bash
echo "Hello, World! -
文件备份:
#!/bin/bash
# 备份文件
cp /path/to/sourcefile /path/to/backupdir -
文件批处理:
#!/bin/bash
# 批量重命名文件
for file in /path/to/files/*.txt; do
mv "$file" "${file%.txt}_new.txt"
done -
条件判断:
#!/bin/bash
# 根据条件执行不同命令
if [ $1 -gt 10 ]; then
echo "Greater than 10"
else
echo "Not greater than 10"
fi -
循环:
#!/bin/bash
# 使用循环输出数字
for i in {1..5}; do
echo "Number: $i"
done -
函数:
#!/bin/bash
# 定义和调用函数
greet() {
echo "Hello, $1!"
}greet "Alice"
-
命令行参数:
#!/bin/bash
# 处理命令行参数
echo "Script name: $0"
echo "First argument: $1" -
读取文件:
#!/bin/bash
# 从文件逐行读取并处理
while IFS= read -r line; do
echo "Line: $line"
done < inputfile.txt