Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

48 Shell scripts using tips

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "48 Shell Script Use Tips". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "48 Shell Script Use Tips" together!

0. shell debugging

The code is as follows:

sh -x somefile.sh

Add set+x set-x to somefile.sh

1. with &&|| simplify if else

The code is as follows:

gzip -t a.tar.gz

if [[ 0 == $? ]]; then

echo "good zip"

else

echo "bad zip"

fi

It can be simplified as:

The code is as follows:

gzip -t a.tar.gz && echo "good zip" || echo "bad zip"

2. Judge file is not empty

The code is as follows:

if [[ -s $file ]]; then

echo "not empty"

fi

3. get file size

The code is as follows:

stat -c %s $file

stat --printf='%s\n' $file

wc -c $file

4. string substitution

The code is as follows:

${string//pattern/replacement}

a='a,b,c'

echo ${a//,/ /}

5. Contains substring?

string="My string"

if [[ $string == *My* ]]; then

echo "It's there! "

fi

6. rsync backup

The code is as follows:

rsync -r -t -v /source_folder /destination_folder

rsync -r -t -v /source_folder [user@host:/destination_folder

7. Batch rename files

Add the.bak suffix to all txt files:

The code is as follows:

rename '.txt' '.txt.bak' *.txt

Remove all the bak suffixes:

The code is as follows:

rename '*.bak' '' *.bak

Change all spaces to underline:

The code is as follows:

find path -type f -exec rename 's/ /_/g' {} \;

Change all file names to capital:

The code is as follows:

find path -type f -exec rename 'y/a-z/A-Z/' {} \;

8. for/while loop

The code is as follows:

for ((i=0; i

< 10; i++)); do echo $i; done for line in $(cat a.txt); do echo $line; done for f in *.txt; do echo $f; done while read line ; do echo $line; done < a.txt cat a.txt | while read line; do echo $line; done 9. 删除空行 代码如下: cat a.txt | sed -e '/^$/d' (echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}' 10. 比较文件的修改时间 代码如下: [[ file1.txt -nt file2.txt ]] && echo true || echo false [[ file1.txt -ot file2.txt ]] && echo true || echo false 11. 实现Dictionary结构 代码如下: hput() { eval "hkey_$1"="$2" } hget() { eval echo '${'"hkey_$1"'}' } $ hput k1 aaa $ hget k1 aaa 12. 去掉第二列 代码如下: $echo 'a b c d e f' | cut -d ' ' -f1,3- $a c d e f 13. 把stderr输出保存到变量 代码如下: $ a=$( (echo 'out'; echo 'error' 1>

&2) 2>&1 1>/dev/null)

$ echo $a

error

14. 删除前3行

代码如下:

$cat a.txt | sed 1,3d

15. 读取多个域到变量

代码如下:

read a b c /dev/null

我们如何在脚本里面重定向呢?没有什么特别之处,和普通重定向一样。

代码如下:

#!/bin/bash

#redirecting output to different locations

echo "now redirecting all output to another location" &>/dev/null

问题就来了,如果我们要将所有的输出都重定向到某个文件呢?我们都不希望每次输出的时候都重定向一下吧,正所谓,山人自有妙计。我们可以用exec 来永久重定向,如下所示:

代码如下:

#!/bin/bash

#redirecting output to different locations

exec 2>testerror

echo "This is the start of the script"

echo "now redirecting all output to another location"

exec 1>testout

echo "This output should go to testout file"

echo "but this should go the the testerror file" >& 2

输出结果如下所示:

代码如下:

This is the start of the script

now redirecting all output to another location

lalor@lalor:~/temp$ cat testout

This output should go to testout file

lalor@lalor:~/temp$ cat testerror

but this should go the the testerror file

lalor@lalor:~/temp$

以追加的方式重定向:

代码如下:

exec 3 >> testout

取消重定向:

代码如下:

exec 3> -

47. 函数

任何地方定义的变量都是全局变量,如果要定义局部变量,需加local 关键字

shell中的函数也可以用递归

代码如下:

#!/bin/bash

function factorial {

if [[ $1 -eq 1 ]]; then

echo 1

else

local temp=$[ $1 - 1 ]

local result=`factorial $temp`

echo $[ $result * $1 ]

fi

}

result=`factorial 5`

echo $result

创建函数库

将函数定一个在另一个文件,然后通过source 命令加载到当前文件

在命令行使用函数

将函数定义在~/.bashrc 中即可

向函数传递数组

代码如下:

#!/bin/bash

#adding values in an array

function addarray {

local sum=0

local newarray

newarray=(`echo "$@"`)

for value in ${newarray[*]}

do

sum=$[ $sum+$value ]

done

echo $sum

}

myarray=(1 2 3 4 5)

echo "The original array is: ${myarray[*]}"

arg1=`echo ${myarray[*]}`

result=`addarray $arg1`

echo "The result is $result"

48.正则表达式

匹配中文字符的正则表达式:[u4e00-u9fa5]

评注:匹配中文还真是个头疼的事,有了这个表达式就好办了

匹配双字节字符(包括汉字在内):[^x00-xff]

评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)

匹配空白行的正则表达式:^ *$

评注:可以用来删除空白行

匹配HTML标记的正则表达式:]*>.*?|

评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力

匹配首尾空白字符的正则表达式:^s*|s*$

评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式

匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*

评注:表单验证时很实用

匹配网址URL的正则表达式:[a-zA-z]+://[^s]*

评注:网上流传的版本功能很有限,上面这个基本可以满足需求

匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$

评注:表单验证时很实用

匹配国内电话号码:d{3}-d{8}|d{4}-d{7}

评注:匹配形式如0511-4405222或021-87888822

匹配腾讯QQ号:[1-9][0-9]{4,}

评注:腾讯QQ号从10000开始

匹配中国邮政编码:[1-9]d{5}(?!d)

评注:中国邮政编码为6位数字

匹配身份证:d{15}|d{18}

评注:中国的身份证为15位或18位

匹配ip地址:d+.d+.d+.d+

评注:提取ip地址时有用

匹配特定数字:

^[1-9]d*$ //匹配正整数

^-[1-9]d*$ //匹配负整数

^-?[1-9]d*$ //匹配整数

^[1-9]d*|0$ //匹配非负整数(正整数+ 0)

^-[1-9]d*|0$ //匹配非正整数(负整数+ 0)

^[1-9]d*.d*|0.d*[1-9]d*$ //匹配正浮点数

^-([1-9]d*.d*|0.d*[1-9]d*)$ //匹配负浮点数

^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$ //匹配浮点数

^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$ //匹配非负浮点数(正浮点数+ 0)

^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$ //匹配非正浮点数(负浮点数+ 0)

评注:处理大量数据时有用,具体应用时注意修正

匹配特定字符串:

^[A-Za-z]+$ //匹配由26个英文字母组成的字符串

^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串

^[a-z]+$ //匹配由26个英文字母的小写组成的字符串

^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串

^w+$ //匹配由数字、26个英文字母或者下划线组成的字符串

感谢各位的阅读,以上就是"48个Shell脚本使用小技巧"的内容了,经过本文的学习后,相信大家对48个Shell脚本使用小技巧这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report