【问题标题】:Parameter checks in bash not testing correctlybash 中的参数检查未正确测试
【发布时间】:2015-07-21 10:38:03
【问题描述】:

我一直在为这个问题摸不着头脑......我试图让我的代码做出如下反应:

If no parameters, go to menu
If more OR less than 4 parameters, call error and go to menu
If exactly 4 parameters, write to file and exit

我无法让它以任何方式工作,如果您能提供帮助,将不胜感激!

username=$1
firstname=$2
surname=$3
password=$4

    if test "$#" = 0; then
    {
    menu 
    }
    elif test "$#" = 4; then
    {
   echo Error
    sleep 2
    menu
    }
    else {
     echo Done
     echo "$firstname" "$surname" >> "$username".log
    echo "$password" >> "$username".log
    curdate=$(date +'%d/%m/%Y %H:%M:%S')
    echo "$curdate" >> "$username".log
    sleep 2
    clear
    exit
    }
    fi

【问题讨论】:

    标签: linux bash command-line command-line-arguments


    【解决方案1】:

    在 bash 中,数字比较不是用 = 完成的,而是用 -eq 及其类似物完成的。 (= 用于字符串比较。)

    所以你想要这样的东西。我将用更常见的[ 符号替换您的test

    if [ "$#" -eq 0 ] ; then
    {
        menu 
    }
    elif [ "$#" -eq 4 ] ; then
    ...
    

    莫特

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-25
      • 2022-01-07
      • 2011-05-19
      • 1970-01-01
      • 2023-03-22
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多