大数据进阶之 shell 脚本开发

目录

shell脚本赋权

1、带索引的 for 循环

2、for循环遍历数组

3、for循环遍历字符串

4、for循环遍历参数

5、if、elif、else和if test

6、while循环和break

7、shell 函数


shell脚本赋权

chmod 777 file.sh

1、带索引的 for 循环

#!/bin/bash
for ((i=0;i<10;i++));do
    echo $i,$(date)
done

2、for循环遍历数组

#!/bin/bash
arr1=(20 21 23 24 25)
arr2=(a b c d e f g)

for i in ${arr1[*]};do
    echo -e $i "\c"
done
echo
for i in ${arr2[@]};do
    echo -e $i "\c"
done
echo
# -e:转义,"\c":不换行
# for循环遍历数组
# ; 为条件结束符
# do 相当于左花括号
# done 相当于右花括号

3、for循环遍历字符串

#!/bin/bash
str="hello world!"
for ((i=0;i<${#str};i++));do
    echo ${str:$i:1}
done

 

4、for循环遍历参数

#!/bin/bash

for i in $*;do
    echo $i
done

5、if、elif、else和if test

arr1=(20 21 23 24 25)
arr2=(a b c d e f g)

if ((${arr1[0]}==$[10]));then
    echo "arr[0]=10"
elif test ${arr1[0]} -eq $[20];then
    echo "arr[0]=20"
elif test ${arr1[0]} -eq 30;then
    echo "arr[0]=30"
else
    echo "arr[0]=-1"
fi

# then 相当于左花括号,然后没有右花括号
# fi为if的字母倒序,表示if语句执行结束

 

6、while循环和break

# while循环
n=20
while (($n>10));do
    echo -e $n "\c"
    ((n--))
done

echo
# while true和break
while true;do
    echo -e "$n" "\c"
    ((n--))
if ((n==0));then
    echo "break"
    break
fi
done

7、shell 函数

# 声明函数
sum(){
    echo "This is a method!"
    n=0
    for i in 1 2 3;do
        ((n+=i))
    done
    return $n
}
# 执行函数sum
sum
# $? 表示函数返回值
echo $?

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章