https://www.runoob.com/w3cnote/shell-quick-start.html
https://www.runoob.com/w3cnote/shell-summary-brackets.html
https://www.runoob.com/w3cnote/linux-command-full-fight.html
https://www.runoob.com/w3cnote/linux-common-command.html
https://www.runoob.com/w3cnote/linux-common-command-2.html
Shebang
在计算领域中,Shebang(也称为Hashbang)是一个由井号和叹号构成的字符序列#!,其出现在文本文件的第一行的前两个字符。 在文件中存在Shebang的情况下,类Unix操作系统的程序加载器会分析Shebang后的内容,将这些内容作为解释器指令,并调用该指令,并将载有Shebang的文件路径作为该解释器的参数
语法Shebang这一语法特性由#!开头,即井号和叹号。 在开头字符之后,可以有一个或数个空白字符,后接解释器的绝对路径,用于调用解释器。 在直接调用脚本时,调用者会利用Shebang提供的信息调用相应的解释器,从而使得脚本文件的调用方式与普通的可执行文件类似。
例子下面列出了一些典型的 shebang 解释器指令:
#!/bin/sh—使用sh,即Bourne shell或其它兼容shell执行脚本#!/bin/csh—使用csh,即C shell执行#!/usr/bin/perl -w—使用带警告的Perl执行#!/usr/bin/python -O—使用具有代码优化的Python执行#!/usr/bin/php—使用PHP的命令行解释器执行
用途解释器指令允许脚本和数据文件充当系统命令,无需在调用时由用户指定解释器,从而对用户和其它程序隐藏其实现细节。
假设/usr/local/bin/foo中有一以下行开头的Bourne shell脚本 #!/bin/sh -x 而它被如此调用("$"是命令提示符) $ foo bar 该命令的输出等同于 $ /bin/sh -x /usr/local/bin/foo bar 除了argv[0]被设定为脚本的文件名,而非解释器的文件名外
在计算领域中,Shebang(也称为Hashbang)是一个由井号和叹号构成的字符序列#!,其出现在文本文件的第一行的前两个字符。 在文件中存在Shebang的情况下,类Unix操作系统的程序加载器会分析Shebang后的内容,将这些内容作为解释器指令,并调用该指令,并将载有Shebang的文件路径作为该解释器的参数
语法
Shebang这一语法特性由#!开头,即井号和叹号。 在开头字符之后,可以有一个或数个空白字符,后接解释器的绝对路径,用于调用解释器。 在直接调用脚本时,调用者会利用Shebang提供的信息调用相应的解释器,从而使得脚本文件的调用方式与普通的可执行文件类似。
例子
下面列出了一些典型的 shebang 解释器指令:
#!/bin/sh—使用sh,即Bourne shell或其它兼容shell执行脚本
#!/bin/csh—使用csh,即C shell执行
#!/usr/bin/perl -w—使用带警告的Perl执行
#!/usr/bin/python -O—使用具有代码优化的Python执行
#!/usr/bin/php—使用PHP的命令行解释器执行
用途
解释器指令允许脚本和数据文件充当系统命令,无需在调用时由用户指定解释器,从而对用户和其它程序隐藏其实现细节。
假设/usr/local/bin/foo中有一以下行开头的Bourne shell脚本 #!/bin/sh -x 而它被如此调用("$"是命令提示符) $ foo bar 该命令的输出等同于 $ /bin/sh -x /usr/local/bin/foo bar 除了argv[0]被设定为脚本的文件名,而非解释器的文件名外
Bash参考手册
https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressionshttps://www.2daygeek.com/6-ways-to-send-email-from-the-linux-command-line/
https://www.2daygeek.com/bash-script-to-delete-files-folders-older-than-x-days-in-linux/
https://www.taniarascia.com/how-to-create-and-use-bash-scripts/
Bash是Unix shell,它是用于与操作系统(OS)进行交互的命令行界面(CLI)。您可以从命令行运行的任何命令都可以在bash脚本中使用。脚本用于运行一系列命令
bash脚本必须始终以bash开头,#!/bin/bash以表示该脚本应使用bash而不是其他任何shell运行。这称为“ shebang”。您可以使用确认bash解释器的位置which bash。
变量
声明的变量不带$,但$在调用时需要,变量和值之间不能有空格
条件
if语句中使用if,then,else,和fi关键字。条件放在方括号中
read 获取用户的输入
#! /bin/bash
echo How old are you?
read age
if [ "$age" -gt 20 ]
then
echo You can drink.
else
echo You are too young to drink.
fi
循环
Bash使用for,while以及until循环。在此示例中,我将使用for...in循环来获取目录中的所有文件并列出它们
#! /bin/bash
FILES=/temp/*
for file in $FILES
do
echo $(basename $file)
done
###Sample-1(simple script)###
#!/bin/sh
# This is a comment!
echo
Hello World
# This is a comment section
###Sample-2(taking decisions)###
#!/bin/bash
if
cp
$
source
$target
then
echo
“File copied successfully”
fi
###Sample-3(simple for loop)###
#!/bin/bash
for
number
in
1 2 3 4 5
do
echo
$number
done
exit
0
# this prints the numbers
###Sample-1(simple script)###
#!/bin/sh
# This is a comment!
echo
Hello World
# This is a comment section
###Sample-2(taking decisions)###
#!/bin/bash
if
cp
$
source
$target
then
echo
“File copied successfully”
fi
###Sample-3(simple for loop)###
#!/bin/bash
for
number
in
1 2 3 4 5
do
echo
$number
done
exit
0
# this prints the numbers
删除文件
# find /tmp -type f -mmin -300 -delete;
# find /tmp -type f -mmin -300 -exec rm -f {} \;
# find /tmp -type f -mmin -300 | xargs rm -f
加可执行权限(chmod +x xxx.sh)
加corntab(corntab -e 添加* * * * * /脚本所在位置/xxx.sh)
https://www.2daygeek.com/bash-script-to-delete-files-folders-older-than-x-days-in-linux/
# /opt/script/delete-old-folders.sh
#! /bin/bash
prev_count=0
fpath=/var/log/app/app_log.*
find $fpath -type d -mtime +10 -exec ls -ltrh {} \; > /tmp/folder.out
find $fpath -type d -mtime +10 -exec rm -rf {} \;
count=$(cat /tmp/folder.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="2daygeek@gmail.com"
echo "Application log folders are deleted older than 15 days" >> $MESSAGE
echo "+----------------------------------------------------+" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/folder.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log files are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/folder.out
fi
# /opt/script/delete-old-files.sh
#! /bin/bash
prev_count=0
fpath=/var/log/apache/2daygeek_access.*
find $fpath -type f -mtime +15 -exec ls -ltrd {} \; > /tmp/file.out
find $fpath -type f -mtime +15 -exec rm -rf {} \;
count=$(cat /tmp/file.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="2daygeek@gmail.com"
echo "Apache Access log files are deleted older than 20 days" >> $MESSAGE
echo "+--------------------------------------------- +" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/file.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log folders are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/file.out
fi
#!/bin/bash
smanager=$(ps -p1 | grep "init\|systemd" | awk '{print $4}')
for serv in rsyslog httpd
do
if (( $(pgrep $serv | wc -l) > 0 ))
then
echo "$serv is running!!!"
elif [ "$smanager" == "init" ]
then
service $serv start
echo "$serv service is UP now.!" | mail -s "$serv service is DOWN and restarted now On $(hostname)" 2daygeek@gmail.com
else
systemctl start $serv
echo "$serv service is UP now.!" | mail -s "$serv service is DOWN and restarted now On $(hostname)" 2daygeek@gmail.com
fi
done
#Set the variable which equal to zero
prev_count=0
count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | egrep -wi 'warning|error|critical' | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
# Send a mail to given email id when errors found in log
SUBJECT="WARNING: Errors found in log on "`date --date='yesterday' '+%b %e'`""
# This is a temp file, which is created to store the email message.
MESSAGE="/tmp/logs.txt"
TO="2daygeek@gmail.com"
echo "ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin." >> $MESSAGE
echo "Hostname: `hostname`" >> $MESSAGE
echo -e "\n" >> $MESSAGE
echo "+------------------------------------------------------------------------------------+" >> $MESSAGE
echo "Error messages in the log file as below" >> $MESSAGE
echo "+------------------------------------------------------------------------------------+" >> $MESSAGE
grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | awk '{ $3=""; print}' | egrep -wi 'warning|error|critical' >> $MESSAGE
mail -s "$SUBJECT" "$TO" < $MESSAGE
#rm $MESSAGE
fi
Bash脚本通过电子邮件警报监视多个远程Linux系统上的磁盘空间使用情况
脚本三部曲:
编辑脚本(vi xxx.sh)加可执行权限(chmod +x xxx.sh)
加corntab(corntab -e 添加* * * * * /脚本所在位置/xxx.sh)
https://www.2daygeek.com/bash-script-to-delete-files-folders-older-than-x-days-in-linux/
# /opt/script/delete-old-folders.sh
#! /bin/bash
prev_count=0
fpath=/var/log/app/app_log.*
find $fpath -type d -mtime +10 -exec ls -ltrh {} \; > /tmp/folder.out
find $fpath -type d -mtime +10 -exec rm -rf {} \;
count=$(cat /tmp/folder.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="2daygeek@gmail.com"
echo "Application log folders are deleted older than 15 days" >> $MESSAGE
echo "+----------------------------------------------------+" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/folder.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log files are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/folder.out
fi
# /opt/script/delete-old-files.sh
#! /bin/bash
prev_count=0
fpath=/var/log/apache/2daygeek_access.*
find $fpath -type f -mtime +15 -exec ls -ltrd {} \; > /tmp/file.out
find $fpath -type f -mtime +15 -exec rm -rf {} \;
count=$(cat /tmp/file.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="2daygeek@gmail.com"
echo "Apache Access log files are deleted older than 20 days" >> $MESSAGE
echo "+--------------------------------------------- +" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/file.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log folders are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/file.out
fi
服务停机时在Linux系统中使用systemd和SysVinit如何自动启动
https://www.2daygeek.com/linux-bash-script-auto-restart-services-when-down/#!/bin/bash
smanager=$(ps -p1 | grep "init\|systemd" | awk '{print $4}')
for serv in rsyslog httpd
do
if (( $(pgrep $serv | wc -l) > 0 ))
then
echo "$serv is running!!!"
elif [ "$smanager" == "init" ]
then
service $serv start
echo "$serv service is UP now.!" | mail -s "$serv service is DOWN and restarted now On $(hostname)" 2daygeek@gmail.com
else
systemctl start $serv
echo "$serv service is UP now.!" | mail -s "$serv service is DOWN and restarted now On $(hostname)" 2daygeek@gmail.com
fi
done
Bash脚本,用于监视Linux中的消息日志(警告,错误和严重)
#!/bin/bash#Set the variable which equal to zero
prev_count=0
count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | egrep -wi 'warning|error|critical' | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
# Send a mail to given email id when errors found in log
SUBJECT="WARNING: Errors found in log on "`date --date='yesterday' '+%b %e'`""
# This is a temp file, which is created to store the email message.
MESSAGE="/tmp/logs.txt"
TO="2daygeek@gmail.com"
echo "ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin." >> $MESSAGE
echo "Hostname: `hostname`" >> $MESSAGE
echo -e "\n" >> $MESSAGE
echo "+------------------------------------------------------------------------------------+" >> $MESSAGE
echo "Error messages in the log file as below" >> $MESSAGE
echo "+------------------------------------------------------------------------------------+" >> $MESSAGE
grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | awk '{ $3=""; print}' | egrep -wi 'warning|error|critical' >> $MESSAGE
mail -s "$SUBJECT" "$TO" < $MESSAGE
#rm $MESSAGE
fi
Bash脚本通过电子邮件警报监视多个远程Linux系统上的磁盘空间使用情况
https://www.2daygeek.com/linux-bash-script-to-monitor-disk-space-usage-on-multiple-remote-linux-systems-send-email/
#!/bin/sh
MESSAGE="/tmp/disk-usage.out"
MESSAGE2="/tmp/disk-usage-1.csv"
echo "Server Name, Filesystem, Size, Used, Avail, Use%, Mounted on" > $MESSAGE2
for server in thvtstrhl7 thvrhel6
for server in `more /opt/scripts/servers-disk-usage.txt`
do
output1=`ssh $server df -Ph | tail -n +2 | sed s/%//g | awk '{ if($5 > 80) print $0;}'`
echo "$server $output1" >> $MESSAGE
done
cat $MESSAGE | grep G | column -t | while read output;
do
Sname=$(echo $output | awk '{print $1}')
Fsystem=$(echo $output | awk '{print $2}')
Size=$(echo $output | awk '{print $3}')
Used=$(echo $output | awk '{print $4}')
Avail=$(echo $output | awk '{print $5}')
Use=$(echo $output | awk '{print $6}')
Mnt=$(echo $output | awk '{print $7}')
echo "$Sname,$Fsystem,$Size,$Used,$Avail,$Use,$Mnt" >> $MESSAGE2
done
echo "Disk Usage Report for `date +"%B %Y"`" | mailx -s "Disk Usage Report on `date`" -a /tmp/disk-usage-1.csv 2daygeek@gmail.com
rm $MESSAGE
rm $MESSAGE2
MySQL / MariaDB数据库备份的简单Shell脚本
#!/bin/sh
MESSAGE="/tmp/disk-usage.out"
MESSAGE2="/tmp/disk-usage-1.csv"
echo "Server Name, Filesystem, Size, Used, Avail, Use%, Mounted on" > $MESSAGE2
for server in thvtstrhl7 thvrhel6
for server in `more /opt/scripts/servers-disk-usage.txt`
do
output1=`ssh $server df -Ph | tail -n +2 | sed s/%//g | awk '{ if($5 > 80) print $0;}'`
echo "$server $output1" >> $MESSAGE
done
cat $MESSAGE | grep G | column -t | while read output;
do
Sname=$(echo $output | awk '{print $1}')
Fsystem=$(echo $output | awk '{print $2}')
Size=$(echo $output | awk '{print $3}')
Used=$(echo $output | awk '{print $4}')
Avail=$(echo $output | awk '{print $5}')
Use=$(echo $output | awk '{print $6}')
Mnt=$(echo $output | awk '{print $7}')
echo "$Sname,$Fsystem,$Size,$Used,$Avail,$Use,$Mnt" >> $MESSAGE2
done
echo "Disk Usage Report for `date +"%B %Y"`" | mailx -s "Disk Usage Report on `date`" -a /tmp/disk-usage-1.csv 2daygeek@gmail.com
rm $MESSAGE
rm $MESSAGE2
MySQL / MariaDB数据库备份的简单Shell脚本
#!/bin/bash
# Add the backup dir location, MySQL root password, MySQL and mysqldump location
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/backup/test-backup"
MYSQL_USER="root"
MYSQL_PASSWORD="***"
MYSQL=/u01/mysql/bin/mysql
MYSQLDUMP=/u01/mysql/bin/mysqldump
# To create a new directory in the backup directory location based on the date
mkdir -p $BACKUP_DIR/$DATE
# To get a list of databases
databases=`$MYSQL -u$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema)"`
# To dump each database in a separate file
for db in $databases; do
echo $db
$MYSQLDUMP --force --opt --skip-lock-tables --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db | gzip > "$BACKUP_DIR/$DATE/$db.sql.gz"
done
# Delete the files older than 10 days
find $BACKUP_DIR/* -mtime +10 -exec rm {} \;
#!/bin/bash
MYSQL_PASSWORD="*****"
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/backup/db-backup"
DB=testdb
mysqldump -u root -p$MYSQL_PASSWORD --all-databases | gzip -9 > "$BACKUP_DIR/all-dbs-$DATE.sql.gz"
find $BACKUP_DIR/* -mtime +5 -exec rm {} \;
#!/bin/sh
#log大小超过10M,保留5次
logsize=`du -m /tmp/monitor.log|awk '{print $1}'`
if [ $logsize -ge 10 ];then
if [ ! -f "/tmp/monitor.log.1" ];then
mv /tmp/monitor.log /tmp/monitor.log.1
elif [ ! -f "/tmp/monitor.log.2" ];then
mv /tmp/monitor.log /tmp/monitor.log.2
elif [ ! -f "/tmp/monitor.log.3" ];then
mv /tmp/monitor.log /tmp/monitor.log.3
elif [ ! -f "/tmp/monitor.log.4" ];then
mv /tmp/monitor.log /tmp/monitor.log.4
elif [ ! -f "/tmp/monitor.log.5" ];then
mv /tmp/monitor.log /tmp/monitor.log.5
else
rm /tmp/monitor.log.1
mv /tmp/monitor.log.2 /tmp/monitor.log.1
mv /tmp/monitor.log.3 /tmp/monitor.log.2
mv /tmp/monitor.log.4 /tmp/monitor.log.3
mv /tmp/monitor.log.5 /tmp/monitor.log.4
mv /tmp/monitor.log /tmp/monitor.log.5
fi
fi
评论
发表评论