如何将参数传递给shell脚本中的已定义函数?

时间:2018-05-13 02:06:24

标签: bash terminal sh

我正在尝试创建一个函数,其中我将两个日期作为参数传递,并将一周的日期记录下来。我已经通过复制和粘贴两个输入日期的解析过程来使它工作,但我试图通过将进程压缩到定义的函数来节省空间。输入应如下所示:

datematch.sh 01/03/1984 06/12/2008

但我不断收到错误信息:

./birthday_match.sh: line 9: ${$1:0:2}: bad substitution
./birthday_match.sh: line 9: ${$1:0:2}: bad substitution
The first person was born on: 
The second person was born on: 
Thus, they were born on the same day.

我如何替换错误?完整的代码如下。

#!/bin/bash
var1=$1
var2=$2
if [ "$#" -ne 2 ]; then
    echo "illegal number of birthdays"
else
    function get_dayname () 
    {
        mo=${$1:0:2}
        dy=${$1:3:2}
        yr=${$1:6:4}
        combo="${mo}${dy}0000${yr}"
        fulldate="$(date $combo 2> /dev/null)"
        wkdy=${fulldate:0:3}
        eval $wkdy
    }
    first=$(get_dayname "$var1")
    second=$(get_dayname "$var2")
    echo "The first person was born on: $first"
    echo "The second person was born on: $second"
    if [ "$first" == "$second" ]; then
        echo "Thus, they were born on the same day."
    else
        echo "Thus, they were not born on the same day."
    fi
fi

0 个答案:

没有答案