shell常用操作
舟率率 12/26/2021 shell
# 循环
# 显示一系列数字
count=1
while [ $count -le 6 ]; do
echo $count
count=$((count + 1))
done
echo "finished"
1
2
3
4
5
6
7
2
3
4
5
6
7
# 指定次数的for循环
for ((i=1;i<=30;i++));
do
source_date=`date -d "-$i day $statistics_date" +%F`
add_retention_step $cluster_id $source_date $statistics_date
if [ "$source_date" = "2017-08-01" ];then
break
fi
done
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 遍历目录下每个文件或目录
# shellcheck disable=SC2045
for name in $(ls "${path}"); do
echo "${name}"
done
1
2
3
4
5
2
3
4
5
# 基于数组长度
path_format(){
path=$1
arr=(/c /d /e /f /g /h /i)
input=${path:0:2}
for format in ${arr[@]}
do
echo ${format}
if [ "${input}" = "${format}" ];then
return 2
fi
done
return 3
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 字符串长度
d='2018/07/26'
${#d}
1
2
2
# 字符串截取
filename='2018-01-01'
year=${filename:0:4}
month=${filename:5:2}
day=${filename:8:2}
echo "year:${year}"
echo "month:${month}"
echo "day:${day}"
1
2
3
4
5
6
7
2
3
4
5
6
7
# 字符串分隔成数组
#!/bin/bash
str="1,2,3,4";
#//与/之间与分割的字符 ,另外/后有一个空格不可省略
str=${str//,/ };
#遍历数组
#此处的*表示索引
for each in ${str[*]}
do
echo $each
done
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 当前文件所在目录
filepath=$(cd "$(dirname "$0")"; pwd)
1
# 判断文件是否存在及是否为空
file="path/file"
# 判断文件是否存在
if ls "${file}"; then
echo "文件存在"
fi
if [[ "$(wc -l "${file}" | grep -E -o '^[0-9]+')" == "0" ]] || [[ "$(cat "${file}")" == "" ]]; then
echo "文件为空"
fi
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# linux之间复制文件和目录
scp -r /data/flink-1.14.6/lib/joda-time-2.10.13.jar root@10.0.18.153:/data/flink-1.14.6/lib/
-r:递归复制整个目录
1
2
3
2
3
# 判断命令是否执行成功
if aws s3 cp filename s3://default_bucket/filename; then
echo "执行成功"
else
echo "执行失败"
exit 1
fi
1
2
3
4
5
6
2
3
4
5
6