为什么 bash 脚本会产生错误“命令未找到”?

214*_*647 0 bash shell

这个脚本中的第五行有什么问题(我已经包含了给我错误的代码片段,实际的错误列在代码后面的底部和完成脚本的链接)?

#! /bin/bash
INSTALLDIR=/usr/local/mapguideopensource
CLEAN_FLAG=0
while [ $# -gt 0 ]; do    # Until you run out of parameters...
  case "$1" in
    -prefix|--prefix)
        INSTALLDIR="$2"
        shift
        ;;
    -clean|--clean)
        CLEAN_FLAG=1
        shift
        ;;
    -help|--help)
        echo "Usage: $0 (options)"
        echo "Options:"
        echo "  --prefix [installation directory]"
        echo "  --clean [clean all objects and binaries in Oem]"
        echo "  --help [Display usage]"
        exit
        ;;
esac
shift   # Check next set of parameters.
done
Run Code Online (Sandbox Code Playgroud)

这是我在 Linux (REHL5) 上运行这个 bash 脚本时遇到的错误:

: command not founde 4:  
: command not founde 8:  
: command not founde 8:  
: command not founde 12:  
MapGuide Open Source build script for OEM components  
'/build_oem.sh: line 17: syntax error near unexpected token `in  
'/build_oem.sh: line 17: `    case "$1" in  
Run Code Online (Sandbox Code Playgroud)

请注意,上面的行号对应于我正在运行的实际脚本(我在下面包含了该脚本的链接) 我正在运行的原始脚本

Gor*_*son 6

从错误中,我很确定行尾有回车符(又名 CR 或 ^M)。Windows/DOS 文本文件在每行末尾都有回车符和换行符,但 UNIX 程序(如 bash)只需要换行符,如果也有 CR,就会感到非常困惑。赠品是错误消息,例如:

: command not founde 4:
Run Code Online (Sandbox Code Playgroud)

这实际上是./build_oem.sh: line 4: ^M: command not found,但是回车符使终端返回到行的开头,并将消息的结尾写在消息的开头上:

./build_oem.sh: line 4: 
: command not found
       |
       V
: command not founde 4:
Run Code Online (Sandbox Code Playgroud)

要修复该脚本,请使用 dos2unix 将其转换为正确的 unix 格式,然后切换到以 unix 格式保存的文本编辑器。