批量建立用户脚本:
#指定了要使用的解释器,这里是 Bash
#!/bin/bash
for i in {1..100}
do
username="std$(printf "%03d" $i)"
password="CentOS"
# 创建用户
sudo useradd -m -s /bin/bash $username
# 设置默认登录口令
echo "$username:$password" | sudo chpasswd
# 第一次登录时要求更改口令
sudo chage -d 0 $username
done
运行脚本:
bash create_users.sh
文件扩展名更名脚本:
#!/bin/bash
# 检查命令行参数的数量是否等于2
if [ "$#" -ne 2 ]; then
# $# 是用于获取传递给脚本的参数个数的特殊变量。
# -ne 是不等于的比较运算符。
# 如果参数数量不正确,输出使用说明。$0 表示脚本自身的名字
echo "Usage: $0 <old_extension> <new_extension>"
exit 1
fi
old_extension="$1"
new_extension="$2"
for file in *."$old_extension"
do
mv "$file" "${file%.$old_extension}.$new_extension"
done
运行脚本(假设脚本名为rename_files.sh):
bash rename_files.sh old_extension new_extension
(old_extension new_extension应该是具体的扩展名例如:
bash txt md)
3. 计算数字参数最大值脚本:
#!/bin/bash
max=0
# 循环遍历传递给脚本的所有参数。
#"$@" 表示所有的命令行参数。
for num in "$@"
do
# 检查当前参数是否大于 max。 -gt 是大于的比较运算符
if [ $num -gt $max ]; then
max=$num
fi
done
# echo "最大值是: $max": 在循环结束后,输出存储在 max 变量中的最大值
echo "最大值是: $max"
运行脚本(假设脚本名为max_value.sh):
bash max_value.sh 5 2 8 3 7
请注意,在实际运行这些脚本之前,你可能需要给脚本文件添加执行权限,例如:
chmod +x create_users.sh rename_files.sh max_value.sh