脚本时一种解释性语言;
shell脚本保存执行动作;
脚本判定命令的执行条件
脚本来实现动作的批量执行。
二、如何创建
vim test.sh ##shell脚本一般都是以.sh结尾
三、执行方法
1.sh test.sh ##不执行开头的的命令
2.chmod +x test.sh
/mnt/test.sh ##执行的时候会先执行以#开头的第一句
sh -x test.sh ##适用于所有脚本
vim test.sh ##脚本必须有X权限
示例一、执行脚本编写的时候自动添加头部
vim /etc/vimrc
"map <F4> ms:call Xniu()<cr>'s ##按快捷键添加
autocmd BufNewFile *.sh,*.script exec ":call Xniu()" ##新建的文件会自动添加
func Xniu()
call append(0,"########################")
call append(1,"# Author : #")
call append(2,"# Date :".strftime("%Y-%m-%d").(" #"))
call append(3,"# Mail : #")
call append(4,"# Version : #")
call append(5,"# #")
call append(6,"########################")
call append(8,"#!bin/bash")
endfunc
示例二:编写脚本显示主机名,ip和可用用户
vim /mnt/show_massage.sh
#!bin/bash
echo "your hostname: "$(hostname)
echo "ip: "$(ifconfig eth0 | grep inet| head -n 1| cut -d " " -f 10)
echo "user for login : "$(grep -E "bash$|tcsh$|sh$|csh$" /etc/passwd |out -d : -f 1)
示例三:编写脚本清空日志
vim /mnt/clear_log.sh ##代码编写如下
#!bin/bash
user=`whoami`
[ "$user" = "root" ]||{
echo -e " 33[31mplease run this script with root! 33[0m"
exit
}&&{
rm -rf /var/log/message /var/log/maillog /var/log/boot.log /var/log/secure
touch /var/log/message /var/log/maillog /var/log/boot.log /var/log/secure
echo clear all
}
示例四:颜色的控制格式
echo -e " 33[40,32m内容 33[0m"
示例五: 对http的端口的修改
vim /mnt/apache_test.sh ##进行脚本的编写
echo Error:Apache is not installed
exit
}
sed "/^Listen/cListen $1" -i /etc/httpd/conf/httpd.conf
systemctl restart httpd
测试:sh /mnt/apache_test.sh 11
netstat -antlupe | grep http ##查看到端口
示例六:用户的创建和删除
[ -z "$mass" ]&&{
read -p "$1 is not exist,you can do this:
[C]reate [S]kip
wha do you what:" choose
[ "$choose" = "C" -o "$choose" = "c" ]&&{
useradd $1
read -p "input passwd:" pas
echo $pas|passwd --stdin $1 &> /dev/null
echo "$1 is create!!"
exit
}
[ "$choose" = "S" -o "$choose" = "s" ]&&{
echo bye!!
exit
}