简体   繁体   English

OSX中的bash语法错误

[英]bash syntax error in OSX

The following bash script, written and tested on Linux, does not even start on OS X when called. 在Linux上编写和测试的以下bash脚本在被调用时甚至无法在OS X上启动。

#!/bin/bash
#
#   Some comments
#
#
function usage {
    echo ""
    echo "Usage: thisscript <SOURCE_DIRECTORY> <TARGET_DIRECTORY>"
    echo ""
    echo "<SOURCE_DIRECTORY>    the directory where the this "
    echo "              directory resides (default is /usr/dis)"
    echo ""
    echo "<TARGET_DIRECTORY>    the destination directory"
    echo ""
}

function notDarwin {
    mv -f $CUR_DIR/* $NEW_DIR/
    ln -sf "$NEW_DIR/ee/sc/scrp" "/usr/bin/scrp"
    ln -sf "$NEW_DIR/ee/etc/conffile.conf" "/etc/conffile.conf"
    exit 0
}

function isDarwin {
    mv -f $CUR_DIR/* $NEW_DIR/
    ln -sf "$NEW_DIR/ee/sc/scrp" "/usr/local/bin/scrp"
    cp "$NEW_DIR/ee/etc/conffile.conf" "/etc/conffile.conf"
    exit 0
}

#
#   =============================================
#   ================== MAIN =====================
#   =============================================
#

CUR_DIR=${1%/}
NEW_DIR=${2%/}

if [ ! -d "$CUR_DIR" ]; then
    echo ""
    echo "blah blah"
    usage
    exit 1
fi

if [ ! -d "$NEW_DIR" ]; then
    echo ""
    echo "The target directory supplied does not exist. Creating target directory $NEW_DIR"
    mkdir "$NEW_DIR"
    if [ $? -ne 0 ]; then
        echo "Could not create target directory. Exiting..."
        exit 1
    else
        echo "Directory $NEW_DIR created"
    fi
    echo ""
fi

UNAME=$(uname)
if [ $UNAME == "Darwin" ]; then
    isDarwin
else
    notDarwin
fi

It throws the following syntax error when run as sudo bash script.sh "arg1" "arg2" on macOS with bash 3.2 在使用bash 3.2的macOS上以sudo bash script.sh "arg1" "arg2"运行时,它将引发以下语法错误

'script.sh: line 7: syntax error near unexpected token `{
'script.sh: line 7: `function usage {

I am rather new to OS X, maybe there is a gotcha I am missing. 我是OS X的新手,也许我缺少一个陷阱。 The script ran fine on Linux... 该脚本在Linux上运行良好...

Thanks 谢谢

Linux and modern OS X expect lines to end with LF (line feed) characters. Linux和现代OS X期望行以LF(换行)字符结尾。 If your lines end with CR + LF, then you will run into problems. 如果您的行以CR + LF结尾,那么您将遇到问题。


Some other general pointers: 其他一些一般性指针:

The function syntax is non-standard. function语法是非标准的。 You should use the standard syntax, supported by all POSIX-compliant shells: 您应该使用所有POSIX兼容外壳程序都支持的标准语法:

Change: 更改:

function usage {

to: 至:

usage() {

and I suspect that all will be well. 我怀疑一切都会好起来的。

As an aside, you should quote all of your parameter expansions (you've missed a couple). 顺便说一句,您应该引用所有参数扩展(您错过了几个)。 It's also considered good practice to use lowercase variable names, as uppercase ones are used by the shell and you run the risk of clashing with them. 使用小写的变量名也被认为是一种好习惯,因为外壳使用大写的变量名,并且冒着与它们冲突的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM