系统之家 - Windows操作系统&装机软件下载网站!

当前位置: 首页  >  教程资讯  >  Linux教程 shell中函数的应用

shell中函数的应用

时间:2024-03-19 10:07:38 来源: 人气:

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下执行脚本,可能会有不同的情况发生,值得注意。

控制输出颜色的shell脚本
实现代码:#!/bin/sh#ANSIColor--Usethesevariablestomakeoutputindifferentcolors#andformats.Colornamesthatendwith'f'areforeground(text)colors,#andthoseendingwith'b'arebackgroundcolors.initializeANSI

linux shell之文件锁
经常在shell脚本里要阻止其它进程,比如msmtp自带的mailqueue脚本,这个脚本的互斥做法是不正确的,下面介绍下发现的三个通过文件达到互斥的正确做法

数值运算shell脚本
这次的shell案例比较简单,但有其特点。#!/bin/sh#scriptbc-Wrapperfor'bc'thatreturnstheresultofacalculation.if[$1="-p"];thenprecision=$2shift2elseprecision=2#defaultfibc-qEOFscale=$precis

教程资讯

Linux教程排行

系统教程

系统主题