Shell 函数接受返回值问题

在shell 常规中,使用命令行堆砌运维命令的方式在代码少的情况可以接受,但是代码不断增长的情况下,则无法清晰进行阅读,开发,维护,所以需要使用函数,而函数之间的涉及可能返回值交互是需要注意的地方,以下是一个简单的栗子:



#! /bin/bash

#根据传入参数 $n,进行相应获取对应的

check_user(){

  n=`cat /etc/passwd  | cut -d ":" -f 1 | grep -n "^$1$" | cut -d ":" -f 1`
  if [ -z "$n"  ];then
     return 0
  else
     return 100
  fi


}




show_userInfo(){


  userinfo=`head -$n /etc/passwd | tail -1 | cut -d ":" -f 1,3,4`
  echo $userinfo




}




echo "input username: "
read username
check_user $username
echo "check_user处理后的状态: $?"




#获取check_user函数 处理参数后的返回值 
num=$?


if [ $num -eq 0 ];then
   echo "The user '$username' is not exist."
   exit
else
  show_userInfo $n




fi


猜你喜欢

转载自blog.csdn.net/dymkkj/article/details/79609241