shell中函数的应用

时间:2021-05-22

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.shinitializeANSIechon "First off, do you have echo in your path? (1=yes, 2=no) "read answerwhile ! validint $answer 1 2 ; do echon "${boldon}Try again${boldoff}. Do you have echo " echon "in your path? (1=yes, 2=no) " read answerdoneif ! checkForCmdInPath "echo" ; then echo "Nope, can't find the echo command."else echo "The echo command is in the PATH."fiecho ""echon "Enter a year you think might be a leap year: "read yearwhile ! validint $year 1 9999 ; do echon "Please enter a year in the ${boldon}correct${boldoff} format: " read yeardoneif 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}"fiexit 0

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

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

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章