【问题标题】:How to call a code that requires a line of code from a user如何调用需要用户一行代码的代码
【发布时间】:2017-04-02 20:49:30
【问题描述】:

我的代码只是在我的 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文件,然后运行而不是必须输入。 question2.bsh(用户名)供它检查。

【问题讨论】:

  • 我建议将[true] 替换为true

标签: bash call options


【解决方案1】:

只需将那些 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 2011-12-15
    • 2015-01-27
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多