函式是shell指令碼中自定義的一些列執行命令,一般來說函式應該設定有返回值(正確返回0,錯誤返回非0)。對於錯誤返回,可以定義返回其他非0正值來細化錯誤。
使用函式的好處是可以避免出現大量重複**,增加了**的可讀性。
定義函式
呼叫函式
函式返回值
函式傳參
function function_name()
hello2()
hello2
[root@servicex script]# ./day05/count_etc.sh
28[root@servicex script]# cat day05/count_etc.sh
#!/usr/bin/bash
#desc:the function can count lines of the /etc/passwd
#author:lalin
#date:2020-04-27
read_file=/etc/passwd
function count()
count
函式的返回值又叫做函式的退出狀態,實際上是一種通訊方式。
[root@servicex script]# ./day05/return_func.sh
please input your file path: /etc/passwd
file exists
[root@servicex script]# ./day05/return_func.sh
please input your file path: /etc/sakjdkajsdlk
no such file
[root@servicex script]# cat day05/return_func.sh
#!/usr/bin/bash
#desc: test function return value
#author:lalin
#date:2020-04-27
read -p "please input your file path: " file_path
function test_file()
test_file
if [ $? -eq 0 ];then
echo "file exists"
else
echo "no such file"
fi
[root@servicex script]# ./day06/parameter.sh /etc/passwd
file exists
[root@servicex script]# ./day06/parameter.sh /etc/passwda
no such file
[root@servicex script]# cat day06/parameter.sh
#!/usr/bin/bash
#desc:
#author:lalin
#date:2020-04-28
function test()
test $1
[root@servicex script]# ./day06/count.sh 2 4
16[root@servicex script]# ./day06/count.sh 2 6
64[root@servicex script]# cat day06/count.sh
#!/usr/bin/bash
#desc:
#author:lalin
#date:2020-04-28
function count()
count $1 $2
除了指令碼執行時傳入指令碼的位置引數外,還可以使用命令set來指定位置引數的值,又叫重置,一旦使用set設定了傳入引數的值,指令碼將忽略執行時傳入的位置引數
[root@servicex script]./day06/set—_func.sh 1 2 3 4
parameter is 20
parameter is 20
parameter is 04
parameter is 28
[root@servicex script]# cat day06/set—_func.sh
#!/usr/bin/bash
#desc:
#author:lalin
#date:2020-04-28
set 20 20 04 28
for i in $@;do
echo "parameter is $i"
done
shell 學習筆記
shell 是解釋型語言 移植性強課對應不同的直譯器 bin sh f 變數開頭以乙個字母或者下劃線,後接任意長度的字母 數字或者下劃線。命令 commod op 引數 輸入 輸出 重定向管道 echo printf 大口如小口出。特殊檔案 dev null bit bucket 刪除所有輸入的資料...
shell學習筆記
shell指令碼在linux下開發經常需要用到,shell的指令碼可以幫助使用者自動化地和作業系統進行互動,起到了提高效率的作用。學習一門語言,通常需要實戰演練編碼除錯,shell該如何除錯呢?使用bash x命令即可。vi demo.sh敲入 bin bash echo 1 echo date y...
shell學習筆記
1 shell檔案的第一行都必須是 bin sh 也可以有其他路徑,這裡我們只以這個為例 2 定義變數 a value 中間不能有空格 呼叫方法 echo a 3 shell常用的條件測試 備註 方括號兩側必須要有空格,f lt等兩側也必須要有空格 a f file 判斷 file是否是乙個檔案 b...