首页 / 网络编程

Shell脚本中使用function(函数)示例

2023-06-22 07:31:53网络编程

函数可以在shell script当中做一个类似自定义执行命令,最大的功能就是可以简化我们很多的程序代码。需要注意的是shell script的执行方式是由上而下/由左而右,因此在shellscript当中的function的设置一定要在程序的最前面,这样才能够在执行时被找到可用的程序段。

#!/bin/bash

# Program

#    This program is to show the use of "function"

# History

# 2013/5/4 by Lvcy First release

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/loacl/sbin:~/bin

export PATH

 

#输出统一信息

function printInfo ()

{

        echo -n "Your choice is "

}

#将小写字符转换为大写字符

function dotr()

{

        tr 'a-z' 'A-Z'

}

read -p "Please input your choice(one|two|three|four):" num

#用case做条件判断

case $num in

        "one")

                printInfo; echo $num | dotr

                ;;

        "two")

                printInfo; echo $num | dotr

                ;;

        "Three")

                printInfo; echo $num | dotr

                ;;

        "four") printInfo; echo $num | dotr

                ;;

esac

exit 0

下面是一个一般的带有function函数的shell脚本:

#!/bin/bash

# Program

#    This program is show the params of function

# History

#    2013/5/14 by Lvcy First release

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin

export PATH

function printInfo()

{

        echo "Your choice is $1"

}

case $1 in

        "one")

                printInfo 1

                ;;

        "two")

                printInfo 2

                ;;

        "three")

                printInfo 3

                ;;

        "four")

                printInfo 4

                ;;

esac

exit 0

若以上文件名为sh02.sh,则执行这个script的命令为:

sh sh02.sh one

csh脚本语法实例
csh实例参考:#!/bin/csh-vx#csh-vxshowthecommandbeforerunningtohelpdebug#justtochecksyntax#csh-n$0#argvif($#argv2)thenecho"Sorry,butyouenteredtoofewparameters"echo"usage:$0arg1arg2exitendifsetarg1

Csh的基本语法介绍
在*unix系统中,常用的shell有sh,bash,csh/tcsh,ksh.sh来自于systemV的Unix,是传统的Unix的shell,直到现在很多的系统管理员仍然喜欢使用sh。bash来自于BSDUnix,

CentOS 6.x系统升级Python到2.7版本的Shell脚本分享
在CentOS6.x上,默认自带的Python是2.6.x版本,这个版本的Python有点老了,比如collections.OrderedDict就是2.7才有的,而且著名的PythonWeb框架Django的新版(如:1.7

想了解相关产品?

扫码添加企业微信,预约演示。

祺平科技企业微信二维码