函数是一串命令的集合,函数可以把大的命令集合分解成若干较小的任务。编程人员可以基于函数进一步的构造更复杂的Shell 程序,而不需要重复编写相同的代码。下面给出了Linux Shell中函数的基本形式
function_name()
{
command1
command2
…
commandN
}
示例一
vim function1.sh
#function1.sh
#!/bin/bash
hello()
{
echo "Hello, today is `date`"
}
echo "Now going to run function hello()"
hello
echo "end the function hello()"
示例二
vim function2.sh
#function2.sh
#!/bin/bash
output()
{
for(( num1 = 1; num1 <= 5; num1++ ))
do
echo -n "$num1 "
done
}
let "num2=1"
while [ "$num2" -le 5 ]
do
output
echo ""
let "num2=num2 + 1"
done
示例三
vim function3.sh
#function3.sh
#!/bin/bash
directory()
{
let "filenum = 0"
let "dirnum = 0"
ls
echo ""
for file in $( ls )
do
if [ -d $file ]
then
let "dirnum = dirnum + 1"
else
let "filenum = filenum + 1"
fi
done
echo "The number of directory is $dirnum"
echo "The number of file is $filenum"
}
directory