Shell基础-10

Tutorial: Shell基础 Category: Shell Published: 2026-04-07 13:58:25 Views: 21 Likes: 0 Comments: 0

Shell 基础-10

  1. trap 命令
#!/bin/bash
# 使用 trap 命令可以拦截用户通过键盘或 kill 命令发送过来的信号
# 使用 kill -l 可以查看 Linux 系统中所有的信号列表,其中 2 代表 Ctrl+C
# trap 当发现有用户 ctrl+C 希望终端脚本时,就执行 echo "暂停 10s";sleep 10 这两条命令
# 另外用户使用命令:[ kill -2 脚本的 PID ] 也可以中断脚本和 Ctrl+C 一样的效果,都会被 trap 拦截

# 即按了Ctrl+C 将执行 trap命令后所有命令
trap 'echo "暂停 2s";sleep 3' 2
while :; do # 死循环
    echo "go go go"
done

  1. 关闭 SELinux
#!/bin/bash

sed -i '/^SELINUX/s/=.*/=disabled/' /etc/selinux/config
setenforce 0
  1. date 的用法
#!/bin/bash
# 00-12 点为早晨,12-18 点为下午,18-24 点为晚上
# 使用 date 命令获取时间后,if 判断时间的区间,确定问候语内容

tm=$(date +%H)

if [ $tm -le 12 ]; then
    msg="Good Morning $USER"
elif [ $tm -gt 12 -a $tm -le 18 ]; then
    msg="Good Afternoon $USER"
else
    msg="Good Night $USER"
fi

echo "当前时间是:$(date +"%Y-%m-%d %H:%M:%S")"
echo -e "\033[34m$msg\033[0m"

  1. 数组用法
#!/bin/bash

i=0
while :; do
    read -p "请输入账户名,输入 over 结束:" key
    if [ $key == "over" ]; then
        break
    else
        name[$i]=$key # 直接给数组赋值
        let i++
    fi
done
echo "总账户名数量:${#name[*]}"
echo "${name[@]}"

  1. 判断存在
#!/bin/bash

if [ $# -eq 0 ]; then
    echo "未输入任何参数,请输入参数"
    echo "用法:$0 [文件名|目录名]"
fi

if [ -f $1 ]; then
    echo "该文件,存在"
    ls -l $1
else
    echo "没有该文件"
fi

if [ -d $1 ]; then
    echo "该目录,存在"
    ls -ld $2
else
    echo "没有该目录"
fi