当前位置: 移动技术网 > 网络运营>服务器>Linux > shell中函数的应用

shell中函数的应用

2017年12月12日  | 移动技术网网络运营  | 我要评论
to turn the functions in this chapter into a library for use in other scripts, extract

to turn the functions in this chapter into a library for use in other scripts, extract all the functions and concatenate them into one big file. if we call this file library.sh, a test script that accesses all of the functions might look like this:

#!/bin/sh

# library test script
. library.sh
initializeansi

echon "first off, do you have echo in your path? (1=yes, 2=no) "
read answer
while ! validint $answer 1 2 ; do
 echon "${boldon}try again${boldoff}. do you have echo "
 echon "in your path? (1=yes, 2=no) "
 read answer
done

if ! checkforcmdinpath "echo" ; then
 echo "nope, can't find the echo command."
else
 echo "the echo command is in the path."
fi

echo ""
echon "enter a year you think might be a leap year: "
read year

while ! validint $year 1 9999 ; do
 echon "please enter a year in the ${boldon}correct${boldoff} format: "
 read year
done

if isleapyear $year ; then
 echo "${greenf}you're right! $year was a leap year.${reset}"
else
 echo "${redf}nope, that's not a leap year.${reset}"
fi

exit 0

应用函数,我们就可以复用我们的脚本。

值得注意的是 $ . tinyscript.sh ,就是在当前shell下执行脚本,不加"."或source

则会在子shell下执行脚本,可能会有不同的情况发生,值得注意。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网