简单的脚本实用技巧

归档压缩

[root@client ~]# tar -zcf boot.tar.gz /boot/* &> /dev/null

[root@client ~]# ls boot.tar.gz
boot.tar.gz

使用多个命令

[root@client ~]# ls ; who
anaconda-ks.cfg boot.tar.gz etc.tar.gz nginx-1.8.0 nginx-1.8.0.tar.gz
root tty1 2019-11-15 21:57
root pts/0 2019-11-15 22:04 (192.168.1.6)

要显示美元符,你必须在它前面放置一个反斜线。

[root@client ~]# echo "The cost of the item is \$15"
The cost of the item is $15

命令替换

[root@client ~]# testing=$(date)
[root@client ~]# echo $testing
2019年 11月 15日 星期五 22:15:57 CST
[root@client ~]# testing1=`date`
[root@client ~]# echo $testing1
2019年 11月 15日 星期五 22:16:19 CST

[root@client ~]# date +%y%m%d
191115

重定向。

扫描二维码关注公众号,回复: 7869058 查看本文章

输出重定向

[root@client ~]# date > testing

[root@client ~]# ls testing
testing

输入重定向

[root@client ~]# wc -l < /etc/passwd
23

[root@client ~]# cat << EOF
> SLDKF
> FDSJL
> EOF
SLDKF
FDSJL

[root@client ~]# sort < /etc/passwd

[root@client ~]# sort < /etc/passwd > passwd.bak

数字运算

[root@client ~]# expr 1 + 8
9
[root@client ~]# expr 1 + a
expr: 非整数参数

[root@client ~]# a=9
[root@client ~]# expr 8 + $a
17
[root@client ~]# echo $?
0
[root@client ~]# expr 1 + a
expr: 非整数参数
[root@client ~]# echo $?
2

[root@client ~]# a=90yu
[root@client ~]# expr 1 + $a
expr: 非整数参数
[root@client ~]# a=7.9
[root@client ~]# expr 1 + $a
expr: 非整数参数

可以用来判断变量的值是否为整数。

[root@client ~]# expr 9 \/ 3    #要使用\进行转义。
3

[root@client ~]# a=2
[root@client ~]# b=3

[root@client ~]# c=$(expr $a + $b)
[root@client ~]# echo $c
5

使用方括号

[root@client ~]# c=$[$a+$b]
[root@client ~]# echo $c
5

[root@client ~]# a=4
[root@client ~]# b=9
[root@client ~]# c=8
[root@client ~]# d=$[$a*($c-$b)]      #中括号里可以使用小括号的。
[root@client ~]# echo $d
-4

浮点数解决方案

[root@client ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1+2
3
3/2
1
1.1+3
4.1

bc命令是可以运算浮点数的。

[root@client ~]# bc -q
a=2
b=9
a+b
11
b/a
4

脚本中使用bc

[root@client ~]# var=$(echo "scale=4; 3.44/5"|bc)  #保留4位小数。
[root@client ~]# echo $var
.6880

bc 命令可以识别输入重定向,允许你将一个文件重定向到bc命令来处理,但这同样会叫人头疼,因为你还得将表达式放到文件中。

test命令

[root@client script]# test 1 -eq 2 && echo "yes" || echo "no"
no

[root@client script]# if test
> then
> echo "yes"
> else
> echo "no"
> fi
no

[root@client script]# [ "$a" \> "$b" ] && echo "yes" || echo "no"
no
[root@client script]# [ "$a" \< "$b" ] && echo "yes" || echo "no"    #比较符号需要转义。r
yes

[root@client script]# char="abc"
[root@client script]# [ -z "$char" ] && echo "yes" || echo "no"
no
[root@client script]# [ -n "$char" ] && echo "yes" || echo "no"
yes

双括命令允许你在比较的过程中使用高等数学表达式,test命令只能使用简单的算术操作,双括号命令提供了更多的数学符号,这些符号对于用过其他编程语言的程序员而言并不陌生,

if (( $var2 ** 2 > 90 ))

[root@client script]# [[ $USER == r* ]] && echo "root" || echo "no root"
root

[root@client script]# case $USER in
> root|ROOT)      |在这里是或的关系。
> echo "root"
> ;;
> esac
root

猜你喜欢

转载自www.cnblogs.com/liujunjun/p/11870126.html