shell函數

1、函數基本格式

function 函數名

{

   命令

}

注:function可以省略

2、函數實例應用

1)創建函數文件

[root@localhost xxx]# cat functions.main 
#!/bin/bash
findit() 
{
 if [ $# -lt 1 ];then
  echo "Usage:findit file"
  return 1
 fi
 find /home -name $1 -print
}

 

2)定位文件

[root@localhost xxx]# . /home/xxx/functions.main

此即<點> <空格> <斜線> <文件名>
3)set  ##檢查載入函數

4)findit 文件名            ##執行載入函數

5)unset findit                ##刪除shell函數

eg1:利用函數處理輸入的名字,名字只能包含大小字母,其它爲非法字符。如果輸入非法字符則提示,直到輸入正確爲止。

#!/bin/bash
function char_name () 
{
 _LETTER_ONLY=$1
 _LETTER_ONLY=`echo $1|awk '{if($0~/[^a-z A-Z]/)print "1"}'`
 if [ "$_LETTER_ONLY" != "" ];then
  return 1
 else
  return 0
 fi
}

function error_name ()
{
 echo "$@ contains error,it must contain only letters"
}

while :
do
 echo -n "Please enter your first name:"
 read F_NAME
 if char_name $F_NAME ;then
  break
 else
  error_name $F_NAME
 fi
done
while :
do
 echo -n "Please enter your last name:"
 read L_NAME
 if char_name $L_NAME ;then
  break
 else
  error_name $L_NAME
 fi
done

 

eg2:列出file.txt文本文件行號

[root@localhost xxxxx]# cat file.txt 
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   37G  3.2G   34G   9% /
devtmpfs               897M     0  897M   0% /dev
tmpfs                  912M     0  912M   0% /dev/shm
tmpfs                  912M  9.0M  903M   1% /run
tmpfs                  912M     0  912M   0% /sys/fs/cgroup
/dev/sda1             1014M  179M  836M  18% /boot
tmpfs                  183M   28K  183M   1% /run/user/0
/dev/sr0               3.8G  3.8G     0 100% /run/media/root/RHEL-7.4 Server.x86_64

[root@localhost xxxxx]# vi number_file.sh 
#!/bin/bash
function file_number ()
{
 _FILE_NAME=$1
 if [ $# -ne 1 ];
 then
   echo "file_number:I need a filename to number"
 fi
 loop=1
 while read line
 do
  echo "$loop:$line"
  loop=`expr $loop + 1`
 done <$_FILE_NAME
}

[root@localhost xxxxx]# . /home/xxxxx/number_file.sh 
[root@localhost xxxxx]# file_number file.txt 
1:Filesystem             Size  Used Avail Use% Mounted on
2:/dev/mapper/rhel-root   37G  3.2G   34G   9% /
3:devtmpfs               897M     0  897M   0% /dev
4:tmpfs                  912M     0  912M   0% /dev/shm
5:tmpfs                  912M  9.0M  903M   1% /run
6:tmpfs                  912M     0  912M   0% /sys/fs/cgroup
7:/dev/sda1             1014M  179M  836M  18% /boot
8:tmpfs                  183M   28K  183M   1% /run/user/0
9:/dev/sr0               3.8G  3.8G     0 100% /run/media/root/RHEL-7.4 Server.x86_64
 

eg3:字符大小寫轉換

#!/bin/bash
function str_to_upper () 
{
 if [ $# -ne 1 ];
 then
  echo "Please enter letters!"
  return 1
 fi
 echo $@|tr [a-z] [A-Z]
}

特別說明:本文是學習David Tansley 《 Linux and UNIX Shell Programming》實體書之後整理的,因本站必需填寫url,文章類型寫成了原創。在此分享,以供大家一起學習。如有不良影響,請聯繫本人刪除。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章