Linux Shell编程——函数

一、Shell 脚本中的函数

脚本中的函数是把一个复杂的语句块定义成一个字符串的方法

1.函数语法

函数名()
{
函数体
函数名
}
例如:

#!/bin/bash
Host_Messages()
{
        read -p "Please input you action:" Action
        [ "$Action" = "exit" ] && exit 0
        [ "$Action" = "user" ] && echo You are $USER
        [ "$Action" = "hostname" ] && echo $HOSTNAME
        Host_Messages
}
2.函数的调用
#!/bin/bash
Host_Messages()
{
        read -p "Please input you action:" Action
        [ "$Action" = "exit" ] && exit 0
        [ "$Action" = "user" ] && echo You are $USER
        [ "$Action" = "hostname" ] && echo $HOSTNAME
        Host_Messages
}
Host_Messages   ##调用函数
3.函数的引用
[root@shellexample mnt]# vim file.sh
#!/bin/bash
Host_Messages()
{
        echo "I like Shell"
}

count=1
while [ "$count" -le "5" ]
do
        Host_Messages
        count=$[ $count + 1 ]
done

echo "End of loop"

Host_Messages
echo "End of script"

[root@shellexample mnt]# sh file.sh 
I like Shell
I like Shell
I like Shell
I like Shell
I like Shell
End of loop
I like Shell
End of script

猜你喜欢

转载自blog.csdn.net/weixin_44209804/article/details/88308587