2016-05-23 78 views
0

我寫了很多次這個函數,但不能正確的..看起來像一個小的語法錯誤,但無法修復它。

function hadleDate{ 
    date=`echo $1|cut -d"." -f1-3` 
    for element in $date; do 
     size=${#element} 
     if [[ $element == 0? ]]; then 
      echo -n $element|cut -c2- 
     elif [[ $size -eq 4 ]]; then 
      echo $element 
     else 
      echo -n $element 
     fi 
    done 
} 
mos="14.03.2013" 
echo handleDate $mos 
+0

你可以張貼嘗試幾件事情後,你的努力? 1.在腳本的開頭添加一行'set -x'並運行以查看問題的根源2.將代碼複製到https://www.shellcheck.net/並修復錯誤警告(s)看到。 – Inian

+0

也改變錯字:不是had ...但是處理... –

回答

4

聲明中的函數名稱後面不能跟{。應該有空格或括號。

function hadleDate() { 
#     ~~ 
+1

它們對於'function'關鍵字是可選的,但'{'之前的空格不是。 – chepner

+0

@chepner:謝謝,重新編寫。 – choroba

0

您可能想要訪問shellcheck.net以查找語法錯誤。

你錯過了,因爲如果和進行網絡連接「爲」

function hadleDate { 
    date=`echo $1|cut -d"." -f1-3` 
    for element in $date; do 
     size=${#element} 
     if [[ $element == 0? ]]; then 
      echo -n $element|cut -c2- 
     elif [[ $size -eq 4 ]]; then 
      echo $element 

     fi 
    done 
    } 
    mos="14.03.2013" 
    echo handleDate $mos 
+1

最相關的是,他忘記了'hadleDate'和'{'之間的空格。 – chepner

+0

是的,確實如此。底線是Shellcheck應該在發佈之前完成:) –

+0

對不起,我是一個新手,仍然在學習如何在這裏工作:) –

0

你handleDate函數試圖削減日期字段,並把它們放入數組。你的變量日期不是一個數組,而只是一個字符串。
你可以不使用這樣的數組:

function handleDate { 
    # Cut fields with dots and use $1 as input for the read. 
    IFS=. read mm dd yyyy <<< "${1}" 
    # Using printf can cut of the zeroes by converting the string to a number 
    printf "%d-%d-%s\n" "${mm}" "${dd}" "${yyyy}" 
} 

mos="14.03.2013" 
handleDate "${mos}" 
相關問題