bash shell tips

shell脚本保留最新的5个文件

#!/bin/sh
echo "删除指定目录下result-order开头的文件,保留最新的5个"
report_dir='/Users/Shared/Jenkins/Home/workspace/pro_env_order'
save_num=5
cd $report_dir
save_file=`ls -lrt | grep 'result-order' | tail -$save_num | awk '{print $NF}'`
ls | grep 'result-order' | grep -v "$save_file" | xargs rm -rf

设置脚本中命令输出时的行宽和行数

export LINES=1000
export COLUMNS=1000

参考:
How to set Cols and Lines for a Subprocess
LINES and COLUMNS environmental variables lost in a script

取日期-1 并设置格式

date -d "1 day ago" '+%Y-%m-%d'
可能存在的问题:我这里测试是正常的,但好像说如果有夏令时可能会有问题,要改成
date -d "yesterday 13:00" '+%Y-%m-%d'
看不太懂,先记下,见参考
参考:Get yesterday's date in bash on Linux, DST-safe

返回一个临时文件全路径

TEMPFILE=mktemp
或者
TEMPFILE=$(mktemp)
参考:Creating temporary files in bash

在shell脚本中执行命令mysql获取输出结果

方法1:

!/bin/bash

mysql -u root -psecret <<MY_QUERY
USE mysql
SHOW tables
MY_QUERY
存在的问题:不能在脚本中将输出重定向到文件
参考:MySQL: Run Query from Bash Script or Linux Command Line
方法2:
mysql -u USER -pPASSWORD -e "SQL_QUERY" > FILE
存在的问题:这个方法只能在console的shell中执行,放到脚本中以后没法执行,会报奇怪的错

方法3:
mysql -s -vvv -hlocalhost -P3306 -uroot -proot <$TEMPFILE >>$LOGFILE 2>&1
通过将需要执行的命令写入临时文件,然后通过标准输入输出调用临时文件来执行,这样是可以的。

取消shell脚本中的 shell 的 pathname 展开

默认shell会对号进行展开,就是把号替换成所在位置路径下的目录和文件名,但我的字符串里有查询语句要用到 ,不能让shell给展开,所以要关掉这个功能
To enable it:
set -o noglob
To disable it:
set +o noglob
还有一种方法没有试
Or also with set -f and set +f.
Yet another method:
shopt -os noglob
and
shopt -ou noglob
参考:
How do I disable pathname expansion in bash?
[关于
星号自动匹配的问题](http://bbs.chinaunix.net/thread-1510785-1-1.html)

shell的单引号和双引号区别

*号的pathname 展开
''(单引号)里面不进行参数展开," "(双引号)里面进行参数展开。
初始化字符串数组
''(单引号)里面按空格进行元素分割," "(双引号)里面按行进行数组分割

参考:
Loop through an array of strings in Bash?

在shell 脚本中,自动输出执行的命令内容

set -v
bash: capturing the output of set -v

输出所有用户邮件到 stdout

echo "type *" | mail
参考:
Read mail from Postfix using shell script
Retrieve Linux local mailbox with command lines non-interactively

1. Print all email to stdout
echo "type *" | mail
echo "type 1" | mail   # print the first email to stdout
echo "type 3-5" | mail # print the emails from 3 to 5

2. Check if mail box is empty (i.e. "No mail for [username]" is found)
echo q | mail 2>&1 | grep "No mail for [username]"

3. Purge the mail box
echo "d *" | mail
echo "d 3" | mail     # Delete the 3rd email

4. Save all emails in a text file
echo "s * test.txt" | mail

5. Save emails between a range in a file
echo "s 3-6 test.txt" | mail
This will save email from #3 to #6 to the file test.txt

6. Read one email from mailbox
echo 1 | mail
Read the first mail from mail box
echo 5 | mail
Read the 5th email from mail box
echo 6 | mail
If there is no 6th mail from mail box. It will prompt you below error:
6: Invalid message number

© 2017 - 2020, 新之助meow. 原创文章转载请注明: 转载自http://www.xinmeow.com

0.00 avg. rating (0% score) - 0 votes
点赞