跳至主要内容

linux 脚本



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]被设定为脚本的文件名,而非解释器的文件名外


Bash参考手册

https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions

https://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



删除文件
# 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


脚本三部曲

编辑脚本(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/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

评论

此博客中的热门博文

自动发送消息

  # https://pyperclip.readthedocs.io/en/latest/ import pyperclip while True :     # pyperclip.copy('Hello, world!')     # pyperclip.paste()     # pyperclip.waitForPaste()     print ( pyperclip. waitForNewPaste ( ) )     # 获取要输入新的坐标,也可以通过autohotkey import time import pyautogui  as pag import os   try :     while True :         print ( "Press Ctrl-C to end" )         x , y = pag. position ( )   # 返回鼠标的坐标         posStr = "Position:" + str ( x ) . rjust ( 4 ) + ',' + str ( y ) . rjust ( 4 )         print ( posStr )   # 打印坐标         time . sleep ( 0.2 )         os . system ( 'cls' )   # 清楚屏幕 except KeyboardInterrupt :     print ( 'end....' )     # 打印消息 import pyautogui import time import pyperclip   content = """   呼叫龙叔! 第二遍! 第三遍! 第四遍...

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

mysql 入门

资料 https://dinfratechsource.com/2018/11/10/how-to-install-latest-mysql-5-7-21-on-rhel-centos-7/ https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html https://www.runoob.com/mysql/mysql-create-database.html https://www.liquidweb.com/kb/install-java-8-on-centos-7/ 工具 https://www.heidisql.com/ HeidiSQL是免费软件,其目标是易于学习。 “ Heidi”使您可以从运行数据库系统MariaDB,MySQL,Microsoft SQL或PostgreSQL的计算机上查看和编辑数据和结构 MySQL 连接时尽量使用 127.0.0.1 而不是 localhost localhost 使用的 Linux socket,127.0.0.1 使用的是 tcp/ip 为什么我使用 localhost 一直没出问题 因为你的本机中只有一个 mysql 进程, 如果你有一个 node1 运行在 3306, 有一个 node2 运行在 3307 mysql -u root -h localhost -P 3306 mysql -u root -h localhost -P 3307 都会连接到同一个 mysql 进程, 因为 localhost 使用 Linux socket, 所以 -P 字段直接被忽略了, 等价于 mysql -u root -h localhost mysql -u root -h localhost 而 -h 默认是 localhost, 又等价于 mysql -u root mysql -u root 为了避免这种情况(比如你在本地开发只有一个 mysql 进程,线上或者 qa 环境有多个 mysql 进程)最好的方式就是使用 IP mysql -u root -h 127 .0 .0 .1 -P 3307 strac...