Home > Software design >  Why is my bash script not recognizing the variable in the date command?
Why is my bash script not recognizing the variable in the date command?

Time:09-27

If I execute this line within a function of my bash script, it runs successfully:

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

But if I pass '2021' as input argument by running

myBash.sh '2021'

I get an error "date: date not valid #-01-01" if I replace the year with the corresponding variable:

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

Also using quotes does not help:

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

Any idea on how to solve it? Thanks in advance!

CodePudding user response:

Functions in bash have their own argument list. As a consequence, they don't have access to the script's argument list.

You need to pass the argument to the function:

#!/bin/bash

# test.sh

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

myFnc "${1}"

Now call the script like this:

bash test.sh 2021

Note: The function keyword in bash has no effect. It just makes the script unnecessarily incompatible with POSIX. Therefore I recommend not to use it.

  • Related