shell(3)shell脚本的基础知识


1.什么是shell

脚本中命令的解释器
解释型语言

2.shell脚本的意义

1.记录命令执行的过程和执行逻辑,以便以后重复执行
2.脚本可以批量处理主机
3.脚本可以定时处理主机

3.如何创建shell脚本

#!/bin/bash ##幻数,表示常量

table键缩进
[root@node2 mnt]# vim ~/.vimrc
autocmd FileType yaml setlocal ai ts=2 sw=2 et
autocmd FileType sh set ai ts=4

4.如何执行shell脚本

1).手动在环境中开启指定解释器。
sh script.sh

2).直接在当前环境中运行shell中的指令不开启新的shell
source script.sh
. script.sh

3).开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x script.sh
/xxx/xxx/script.sh
./script.sh

区别:

1)新开了shell,开设了子进程,与原始进程不共享。2)3)没有开

5.如何对脚本进行调试

sh -x /mnt/westos.sh

  • +##表示运行指令
  • 不带+ ##命令运行的输出
脚本练习:

1.ip_show.sh 网卡 显示当前的ip
2.host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
3.clear_log.sh 执行次脚本后可以清空日志

1,ip_show.sh 网卡	显示当前的ip
[root@node2 mnt]# vim ip_show.sh 
echo "ipaddress:$(ifconfig enp1s0 | awk '/inet\>/{print $2}')"
[root@node2 mnt]# sh ip_show.sh enp1s0
172.25.254.203
2,[root@node2 mnt]# vim host_message.sh 
#!/bin/bash
echo "hostname:$HOSTNAME"
echo "ipaddress:$(ifconfig enp1s0 | awk '/inet\>/{print $2}')"
echo "useranme:$(whoami)"
#echo "useranme:$USER"
[root@node2 mnt]# sh host_message.sh 
hostname:localhost.localdomain
ipaddress:172.25.254.203
useranme:root

在这里插入图片描述在这里插入图片描述

3,[root@node2 mnt]# vim clear_log.sh
#!/bin/env bash
[ "$USER"="root" ] || {
        echo -e "\033[31mError:please run script with root!!\033[0m"
        exit 1
}
LOGS=`sed -n '/RULES/,$p' /etc/rsyslog.conf |awk '!/^#|^$/&&/var/{print $2}' | sed 's/-//g'`
for LOG in $LOGS
do      
        > $LOG && echo -e '\033[32m$LOG is cleared!!\033[0m'
done    
[root@node2 mnt]#sh clear_log.sh

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qiao_qing/article/details/111567038