2016-02-15 21 views
0

这里是我的脚本:为什么在运行bash脚本时出现意外的文件错误结束?

#!/bin/bash 
if [ $# -lt 2 || $# -gt 3 ]; then # invalid number of arguments given 
    echo "usage: minor3 name [euid]" 
else # valid number of arguments given 
    echo Good day, $1! Nice to meet you! 
    CHOICE=1 
    while [ "$CHOICE" -gt 0 && "$CHOICE" -lt 4 ] # print out the menu, obtain user choice, execute appropriate system call using if-else statements, loop if desired 
    do 
     echo "+*******************************************************************+ 
       Enter one of the following options:         | 
       1) List and count all non-hidden files in the current directory. | 
       2) Check if given user (default = current user) is logged in, then | 
       ... list all active processes for that user.      | 
       3) List the sizes and names of the 10 largest files and directories | 
       ... in the current directory.          | 
       4) Exit this shell program.           | 
       +*******************************************************************+ 
       > "  
     read CHOICE 
     if [ "$CHOICE" = 1 ]; then 
      # list and count all files 
      echo test 
     fi 
     if [ "$CHOICE" = 2 ]; then 
      if [ $# = 3 ]; then # euid was given 
       # use given user ($2) 
       echo given user 
      else 
       # use current user 
       echo current user 
      fi 
     fi 
     if [ "$CHOICE" = 3 ]; then 
      # list sizes and names of 10 largest files/directories 
      echo test 
     fi 
    done 
    echo Thanks, $1! Have a great day! 
fi 

这是我得到的错误:51

[email protected]:~/3600/min3$ chmod +x minor3.sh 
[email protected]:~/3600/min3$ ./minor3.sh 
./minor3.sh: line 51: syntax error: unexpected end of file 

线是最后fi后的行,即最后一行后,我行程序。我发现一个较早的堆栈溢出的职位,说要用DOS2UNIX的,但是Linux服务器一定要考就由我校拥有的,所以我没有把它安装能力,使得它不是一个选项。服务器使用Linux Ubuntu 12.04.5 LTS,如果这有所作为。

+1

如果我复制你的代码片段并将其粘贴到我的Vim,他最后'fi'是39行,不就行了50 ... – eckes

+0

也许只是一个格式差异。整个计划在那里。 –

+1

@eckes错误的行号来自dos与unix行结束问题。 – jofel

回答

2

不能使用&&||[ ... ]这只是调用 的test command

使用-a-o代替或使用两个[...]表达式:

if [ "$#" -lt 2 ] || [ "$#" -gt 3 ] ; then 

另一种方式是使用内置的bash [[ ... ]]操作。 它允许使用&&||

if [[ "$#" -lt 2 || "$#" -gt 3 ]]; then 

程序也崩溃,如果你不进入 一个号码,只需键入输入。如果$CHOICE为空,请至少检查 。

看来你有CRLF行结束(类似于DOS), 例如使用

perl -pi -e 's/\r\n/\n/g' -- YOURSCRIPTNAME.sh 

确实解决了这个问题。这效仿dos2unix

+0

@ColeDapprich我伸出我的回答你的代码。 – jofel

+0

不要使用'-a'和'-o';他们都被弃用。 – chepner

+0

@chepner这将是很好,如果你可以勾勒“现代”的方式和它的优点,比如我可以优化答案。 – jofel

相关问题