Gpp094
Gpp094

Reputation: 35

Why is my bash script not recognizing the variable in the date command?

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!

Upvotes: 0

Views: 247

Answers (1)

hek2mgl
hek2mgl

Reputation: 158020

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.

Upvotes: 5

Related Questions