【问题标题】:Why is my bash script not recognizing the variable in the date command?为什么我的 bash 脚本无法识别 date 命令中的变量?
【发布时间】:2021-11-18 22:11:04
【问题描述】:

如果我在我的 bash 脚本的函数中执行这一行,它会成功运行:

function myFnc(){
...
variable1=$(date -d 2021-01-01 +%W)
...
}

但如果我通过运行将“2021”作为输入参数传递

myBash.sh '2021'

如果我将年份替换为相应的变量,则会收到错误“日期:日期无效 #-01-01”:

function myFnc(){
...
variable1=$(date -d $1-01-01 +%W)
...
}

同样使用引号也无济于事:

function myFnc(){
...
variable1=$(date -d "$1-01-01" +%W)
...
}

知道如何解决它吗?提前致谢!

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: bash positional-parameter


【解决方案1】:

bash 中的函数有自己的参数列表。因此,他们无权访问脚本的参数列表。

您需要将参数传递给函数:

#!/bin/bash

# test.sh

myFnc() {
    variable1=$(date -d "${1}"-01-01 +%W)
    echo "${variable1}"
}

myFnc "${1}"

现在像这样调用脚本:

bash test.sh 2021

注意:bash 中的function 关键字无效。它只是使脚本不必要地与 POSIX 不兼容。因此我建议不要使用它。

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多