スクリプトは入力がコマンドだと思いますか?

スクリプトは入力がコマンドだと思いますか?

私は基本的なシェルコマンドを実行するスクリプトの作成を始めましたが、2番目の関数(有効な年と月を取得し、それを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

この行には(一般的な)構文エラーがあります(まあ、2つ以上...)。

[$year>1]
  1. [特殊文字ではなく一般命令です。したがって、行の残りの部分はパラメータであるため、スペースで区切る必要があります。[ "$year" > 1 ]

  2. 次の問題は、これが>一般的なパラメータではなくリダイレ​​クト文字(メタ文字)であることです。したがって、シェルは(たとえば)[2014その名前のコマンドを表示して検索します。シェルは出力をファイルに書き込みます(存在する場合1])。

次のように使用する場合は、[ ... ]演算子(より大きい)が必要です-gt

[ "$year" -gt 1 ]

bash別のアプローチは、予約語を[[代わりに使用することです[。それでもスペースを区切り文字として使用する必要がありますが、引用符は省略できます。

[[ $year -gt 1 ]]

あるいは、算術式を使用して整数を比較することもできます。

((year > 1))

おすすめ記事