日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Shell函數返回值方式_linux shell

作者:AllardZhao ? 更新時間: 2022-09-29 編程語言

1、返回值的方式:

  • 方法一:return
  • 方法二: echo

2、return和echo使用場景區別:

(1).使用return返回值:

  • 使用return返回值,只能返回1-255的整數
  • 函數使用return返回值,通常只是用來供其他地方調用獲取狀態,因此通常僅返回0或1;0表示成功,1表示失敗

(2).使用echo返回值:

  • 使用echo可以返回任何字符串結果
  • 通常用于返回數據,比如一個字符串值或者列表值

3、場景示例

(一) return使用場景

函數通過return返回一個整數,這種場景通常是用來做判斷的,也就是說在執行完函數之后,需要根據它的返回值做判斷,通0表示成功,非0都是表示失敗。

#!/bin/bash
?
this_pid=$$
# 判斷nginx進程是否正在運行
function is_nginx_running
{
?? ?ps -ef | grep nginx | grep -v grep | grep -v $this_pid &>/tmp/null
?? ?if [ $? -eq 0 ];then
?? ??? ?# return 0,也可以省略0直接return,兩個是等價
?? ??? ?return
?? ?else
?? ??? ?return 1
?? ?fi
}
# return在函數中的返回值,只是用來做狀態判斷的,根據狀態值做下一步判斷
# 函數的返回值為0時,表示nginx服務運行正常輸出 && 后字符串,否則返回 ||后字符串
is_nginx_running && echo "Nginx is running" || echo "Nginx is stoped"
?
?
# 運行腳本
~ % sh 29.echo_return_nginx.sh
Nginx is stoped
~ % sudo nginx ?# Mac 使用,Linux為 systemctl start nginx?
~ % sh 29.echo_return_nginx.sh
Nginx is running

(二) echo使用場景

函數通過echo返回值,通常是返回數據用的,以供程序的其它地方使用。

#!/bin/bash
?
# 獲取整個Linux系統上所擁有的所有用戶
function get_users
{
?? ?# users=`cat /etc/passwd | cut -d: -f1` # linux使用
?? ?# Mac 使用
?? ?users=`cat /etc/passwd | tail -n+11 | cut -d: -f1 | cut -d_ -f2`
?? ?echo $users
}
?
# 執行該函數,返回值為用戶列表
# get_users
?
# 遍歷用戶列表對用戶名做處理
user_list=`get_users`
index=1
for user in $user_list
do
?? ?echo "This $index user is : $user"
?? ?index=$(($index+1))
done
?
?
# 運行腳本
~ % sh 30.echo_sys_user.sh
This 1 user is : nobody
This 2 user is : root
... ...
This 109 user is : oahd

原文鏈接:https://blog.csdn.net/qq_37189082/article/details/121894595

欄目分類
最近更新