Linux基础之Shell脚本常用命令
#!/bin/sh
1 取脚本参数
$# 参数个数
$0 当前脚本名
$1 第1个参数
$n 第n个参数
$* 所有参数
$@ 所有参数
$? 上个命令的状态
$$ 当前pid
取当前目录
$(cd `dirname $0`; pwd)
2 日期
$ date
Wed Mar 27 17:27:18 CST 2019
$ date +"%Y-%m-%d %H:%M:%S"
2019-03-27 17:28:27
$ date +"%Y-%m-%d %H:%M:%S" --date="-1 day"
2019-03-26 17:29:10
$ date +%s
1553678982$ date -d "-1day2019-05-20" +%Y%m%d
20190519$ date -d"$(date -d"1 month" +"%Y%m01") -1 day" +"%Y%m%d"
20190531$ date +"%Y%m$(cal|sed 'N;${s/.* //;P;d};D')"
20190531
3 字符串替换
将变量var中的a全部替换成b
${var//a/b}
echo "$var"|awk 'gsub("a","b") {print $0}'
echo "$"|sed 's/a/b/'
4 字符串截取子串
var=hello
echo ${#var}
echo $var|awk '{print substr($0, 2, 3)}'
echo ${var:2}
echo ${var:2:3}echo ${var#he}
echo ${var%lo}echo ${var1:`echo $((${#var2}+1))`}
5 字符串split
数组(item本身不能包含空格)
str=${str//,/ } for item in $str do echo $item done
cut(cut: the delimiter must be a single character 分隔符只能为1个字符)
i=1 while((1==1)) do item=`echo $str|cut -d "," -f$i` if [ "$item" != "" ] then ((i++)) echo $item else break fi done
awk -F(索引位置只能硬编码)
$ echo $str|awk -F ',' '{print $1}
awk split
$ echo $str|awk '{split($0,arr,","); for (i in arr) {print arr[i]}}'
6 循环
字符串循环(空格分割)
var='1 2 3'
for var in $vars
do
echo $var
done
整数循环(从1到100)
for i in {1..100}
do
echo $i
done
自增id
i=0
for var in $vars
do
echo "$i $var"
((i=i+1))
done
while
#while true
while [ 1 -eq 1 ]
do
..
break/continue
..
done
7 字符串是否为空判断(相等、不等)
if [ -z "$var" ]
then
echo "var is empty"
fiif [ -n "$var" ]
then
echo "var is not empty"
fiif [[ "$var" = "" ]]
then
echo "empty"
fiif [[ "$var" != "" ]]
then
echo "not empty"
fi
8 字符串包含判断
if [[ "$all" == *"$sub"* ]]; then
or
if [[ "$all" =~ "$sub" ]] ;then
9 整数比较判断
if [ $a -eq 0 ]
then
echo "a = 0"
fi
if [ $a -ne 0 ]
then
echo "a != 0"
fi
if [ $a -gt 0 ]
then
echo "a > 0"
fi
if [ $a -lt 0 ]
then
echo "a < 0"
fi
10 if
if-else
if cond; then
...
elif cond; then
...
else
...
fi
布尔连接AND OR
if [ $a -lt 0 -a -z "$b" ]; then
echo ''
fi
或者
if [ $a -lt 0 ] && [ -z "$b" ]; then
echo ''
fi
以上为AND,替换 -a -> -o, && -> || 后为OR
11 整数计算
echo $((2+1))
12 注释
单行注释
# comment
多行注释
<<'COMMENT'
comment1
comment2
...
COMMENT
13 文件和文件夹判断
if [ -d "/path/to/dir" ]
then
echo 'directory /path/to/dir exists'
else
echo 'directory /path/to/dir does not exists'
fiif [ -f "/path/to/file" ]
then
echo 'file /path/to/file exists'
else
echo 'file /path/to/file does not exists'
fi
14 遍历文件夹
dir=/path/to/dir/
for file in $dir/*
do
echo $file
done
15 退出脚本
exit 0
exit 1
---------------------------------------------------------------- 结束啦,我是大魔王先生的分割线 :) ----------------------------------------------------------------
- 由于大魔王先生能力有限,文中可能存在错误,欢迎指正、补充!
- 感谢您的阅读,如果文章对您有用,那么请为大魔王先生轻轻点个赞,ありがとう