簡體   English   中英

OSX中的bash語法錯誤

[英]bash syntax error in OSX

在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

在使用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 {

我是OS X的新手,也許我缺少一個陷阱。 該腳本在Linux上運行良好...

謝謝

Linux和現代OS X期望行以LF(換行)字符結尾。 如果您的行以CR + LF結尾,那么您將遇到問題。


其他一些一般性指針:

function語法是非標准的。 您應該使用所有POSIX兼容外殼程序都支持的標准語法:

更改:

function usage {

至:

usage() {

我懷疑一切都會好起來的。

順便說一句,您應該引用所有參數擴展(您錯過了幾個)。 使用小寫的變量名也被認為是一種好習慣,因為外殼使用大寫的變量名,並且冒着與它們沖突的風險。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM