[root@hadoop1 bash]# vi hello
#!/bin/bash
echo "hello world"
[root@hadoop1 bash]# chmod 777 hello
[root@hadoop1 bash]# ./hello
hello world
[root@hadoop1 bash]# sh hello
hello world
if condition then statements [elif condition then statements. ..] [else statements ] fi
实例:
[root@hadoop1 bash]# vi ifTest
#!/bin/bash
read -p "please input your name:" NAME
#printf '%s\n' $NAME
if [ $NAME = root ]
then
echo "hello ${NAME}, welcome !"
elif [ $NAME = **** ]
then
echo "hello ${NAME}, welcome !"
else
echo "SB, get out here !"
fi
[root@hadoop1 bash]# chmod 777 ifTest
[root@hadoop1 bash]# sh ifTest
please input your name:root
hello root, welcome !
实例一:
while expression
do
command
…
done
实例代码一:
[root@hadoop1 log]# while true
> do
> date >> test.log
> sleep 1
> done;
实例二:
i=1
while ((i<=3))
do
echo $i
let i++
done
case $1 in
start)
echo "starting"
;;
stop)
echo "stoping"
;;
*)
echo "Usage: {start|stop}"
esac
方式一:
for N in 1 2 3
do
echo $N
done
或
for N in 1 2 3; do echo $N; done
或
for N in {1..3}; do echo $N; done
方式二:
for ((i = 0; i <= 5; i++))
do
echo "welcome $i times"
done
或
for ((i = 0; i <= 5; i++)); do echo "welcome $i times"; done
# func1.sh
hello() ## 函数定义
{
echo "Hello there today's date is `date +%Y-%m-%d`"
# return 2 ###返回值其实是状态码,只能在[0-255]范围内
}
echo "now going to the function hello"
hello
# echo $? 获取函数的return值
echo "back from the function"
函数调用:
function hello()
或 function hello
或 hello
#!/bin/bash
# fun1.sh
funWithParam(){
echo "第一个参数为 $1 !"
echo "第二个参数为 $2 !"
echo "第十个参数为 $10 !"
echo "第十个参数为 ${10} !"
echo "第十一个参数为 ${11} !"
echo "参数总数有 $# 个!"
echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
注意,10 不能获取第十个参数,获取第十个参数需要{10}。当n>=10时,需要使用
#!/bin/bash
# fun2.sh
funWithReturn(){
echo "这个函数会对输入的两个数字进行相加运算..."
echo "输入第一个数字: "
read aNum
echo "输入第二个数字: "
read anotherNum
echo "两个数字分别为
return ((aNum+
}
funWithReturn
echo "输入的两个数字之和为 $? !"
存在 /root/fun2.sh
可在fun_other.sh中调用apt install htop
#!/bin/bash
# fun_other.sh
. /root/fun2.sh ## 注: . 和 / 之间有空格
# 或者 source /root/fun2.sh
funWithParam 11 22 33 44 55 66 77 88 99 100 101