如何调用需要用户代码行的代码

时间:2016-11-18 22:01:35

标签: bash call options

我的代码只检查passwd文件中的用户。

#!/bin/bash

ret=false
getent passwd "$1" >/dev/null 2>&1 && ret=true

if $ret; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

它工作正常,你只需按名称调用它:。 problem2.bsh(用户名),它测试用户是否在我的passwd文件中。工作良好。但我想将它与其他2个代码一起放入一个方法,让我可以选择调用它。 例如:

while [true]
do
  case $option in
  a) . problem1.bsh
     ;;
  b) . problem2.bsh
     ;; 
  c) . problem3.bsh
     ;;
  x) break
     ;;
  *) echo "invalid input"
 esac
done

选项a和c,在调用问题1和3时工作正常但由于某种原因问题2不会返回任何内容。 反正有问题2要求用户名先检查我的passwd文件然后运行而不是必须输入。 problem2.bsh(用户名)供它检查。

1 个答案:

答案 0 :(得分:0)

只需将这些problem*.bsh文件转换为函数并使用全局变量,如:

problem1() { echo $user ... ; }
problem2() { getent passwd "$user" ; }
problem3() { echo ... "$user" ; }
user=$1
while true
do printf 'option [abcx]? '
 read -r
 case $REPLY in
  a) problem1 ;;
  b) problem2 ;;
  c) problem3 ;;
  x) break ;;
  *) echo "invalid input" ;;
 esac
done