【问题标题】:How do I pass arguments to a defined function in a shell script?如何将参数传递给 shell 脚本中定义的函数?
【发布时间】:2018-10-23 00:57:51
【问题描述】:

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

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

【问题讨论】:

  • 它是${1:0:2}。错误是额外的$
  • 另外,你为什么使用eval?你可能想要 `echo "$wkdy"。

标签: bash terminal sh


【解决方案1】:

参数扩展语法不正确:

mo=${$1:0:2}

应该是

mo=${1:0:2}

考虑简单的情况。将第一个参数原样替换为$1${1}。在第二个版本中,大括号用于将变量名称或编号与后面的内容分开。

如果你写${$1},直观的意思是“把第一个参数当作一个名字,用那个这个名字代替变量的值”....但是bash参数扩展语法不允许这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2015-10-09
    • 1970-01-01
    • 2021-04-16
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多