脚本认为输入是命令?

脚本认为输入是命令?

我刚刚开始编写一个执行基本 shell 命令的脚本,但第二个函数(应该采用有效的年份和月份并将其插入 cal)返回时出现以下错误:

Enter the year:
2014
/home/duncan/menuscript.sh: line 34: [2014: command not found
/home/duncan/menuscript.sh: line 34: [2014: command not found
This is an invalid year

这是我正在处理的代码,我已经寻找了答案,但我不明白为什么它无法编译..我不是试图输入日期作为命令!

#!/bin/bash
echo "Welcome to Duncan's main menu"
function press_enter
{
    echo ""
    echo -n "Press Enter to continue"
    read
    clear
}
year=
month=
selection=
until [ "$selection" = "9" ] 
do
  clear
  echo ""
  echo "    1 -- Display users currently logged in"
  echo "    2 -- Display a calendar for a specific month and year"
  echo "    3 -- Display the current directory path"
  echo "    4 -- Change directory"
  echo "    5 -- Long listing of visible files in the current directory"
  echo "    6 -- Display current time and date and calendar"
  echo "    7 -- Start the vi editor"
  echo "    8 -- Email a file to a user"
  echo "    9 -- Quit"
  echo ""
  echo "Make your selection:"
  read selection
  echo ""
  case $selection in
    1) who ; press_enter ;;
    2) echo "Enter the year:" ;
       read year ;
       if [$year>1] || [$year<9999]; then
         echo "Enter the month:" 
         read month
         if [0<$month<12]; then
           cal -d $year-$month 
           press_enter
         else
           echo "This is an invalid month"
           press_enter
         fi
       else
          echo "This is an invalid year"
          press_enter 
       fi ;;

    9) exit ;;
    *) echo "Please enter a valid option" ; press_enter ;;
   esac
done

答案1

这一行有一个(常见的)语法错误(好吧,不止一个......):

[$year>1]
  1. [不是特殊字符而是普通命令。因此,该行的其余部分是参数,并且必须用空格分隔:[ "$year" > 1 ]

  2. 下一个问题是这>不是普通参数而是重定向字符(元字符)。因此,shell 会看到(例如)[2014并查找具有该名称的命令。如果有的话,shell 会将其输出写入文件1]......

如果使用[ ... ]则需要运算符-gt(大于):

[ "$year" -gt 1 ]

另一种方法是使用bash保留字[[代替[。您仍然必须使用空格作为分隔符,但可以省略引号:

[[ $year -gt 1 ]]

或者您可以使用算术表达式来比较整数:

((year > 1))

相关内容