linux shell命令之函数的定义和基本知识
1. 简单的hello函数调用
cat function1.sh
vi function1.sh
#!/bin/bash
#建立一个简单的函数hello
hello()
{
echo "Hello everyone!"
}
#调用hello函数
echo "Now going to run function hello()"
hello
#提示结束函数调用
echo "end the function hello()"
./function1.sh
Now going to run function hello()
Hello everyone!
end the function hello()
打出5行(1 2 3 4 5)
vi function2.sh
#!/bin/bash
#该函数用于在一行中显示1 2 3 4 5
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
./function2.sh
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
判断当前目录下存在多少个文件和子目录
vi function3.sh
#!/bin/bash
#判断当前目录中存在多少个文件和多少个子目录
directory()
{
let "filenum = 0"
let "dirnum = 0"
#显示当前目录下的所有的子目录和文件,并使用echo 换行
ls $1
echo ""
#使用for循环判断当前子目录和文件,并使用echo换行
for file in $( ls )
do
if [ -d $file ]
then
let "dirnum=dirnum + 1" #判断为子目录
else
let "filenum=filenum + 1" #判断为文件,文件个数加1
fi
done
#使用echo命令显示当前子目录和文件个数
echo "The number of directories is $dirnum"
echo "The number of files is $filenum"
}
#脚本调用函数
directory
./function3.sh
anotherres.sh execerr.sh llac PEO.dbab sturecord timedread.sh
a.out execin.sh loggg PEO.dbac subscol.sh timer1
append.sed execout.sh MapClearTest.class PROFESSOR.db subsenv.sh timer1.c
AREACODE.db FILE1 MapClearTest.java refor.sh subsep.sh timer2
argv.awk FILE2 modify.sed reif.sh subsig.sh timer2.c
awk.dll.gz findphone.awk mysql_test.c REPEAT subsparallel.sh timer3
backls.sh forever.sh newfile resshell.sh subsvar.sh timer3.cpp
calare.sh function1.sh nokillme.sh rewhile.sh TEACHER1.db traploop.sh
CARGO3.db function2.sh output scr2.awk TEACHER.db traverseFile
conlon.sh function3.sh outputnull scr.awk TEACHER_HOBBY.db traverseFile.c
count_word.sh hfile part1 selfkill.sh test1.c vartype.sh
doubleparenthese.sh indirectapp1.sh part2 sever.c test1.cpp WORDLIST
e_sleep57.sh indirect.sh part3 sever.o test.c xaa
evalpos.sh insert.sed parttotal sever.s testNet.c xab
evalre.sh llaa pass.awk sleep10.sh test_sockpair xac
evalsource llab PEO.dbaa sleep55.sh test_sockpair.c
The number of directories is 0
The number of files is 95
浙公网安备 33010602011771号