Alain Bourgeois
Alain Bourgeois

Reputation: 89

bash - command in a variable - issue with quotes

I want to store the date of last Sunday in a variable.

#/bin/bash

OFFSET=$(date +%u)
COMMAND="date --date='"$((OFFSET))" days ago' +%Y%m%d"
DATEFULL=$($COMMAND)

echo offset $OFFSET
echo command $COMMAND
echo datefull $DATEFULL

Output:

[root@localhost ~]# ./test.sh
date: extra operand ‘ago'’
Try 'date --help' for more information.
offset 1
command date --date='1 days ago' +%Y%m%d
datefull

Pasting the result of $COMMAND in command line gives the right result:

[root@localhost ~]# date --date='1 days ago' +%Y%m%d
20210822

So why does he claim about "date: extra operand ‘ago'’" ? How can I execute the result of command and set it in a variable?

Upvotes: 0

Views: 72

Answers (2)

Philippe
Philippe

Reputation: 26452

Try to use arrays for commands, instead of variables :

#!/bin/bash

OFFSET=$(date +%u)
COMMAND=(date "--date=$OFFSET days ago" +%Y%m%d)
DATEFULL=$("${COMMAND[@]}")

echo offset $OFFSET
echo command $COMMAND
echo datefull $DATEFULL

Also all uppercase variable names can cause clashes with bash-defined variables.

Upvotes: 2

Bayou
Bayou

Reputation: 3441

I'm unsure why this doesn't work. I think it has something to do with bash parsing quotes out of the command. If you use eval, it works:

#/bin/bash

OFFSET=$(date +%u)
COMMAND="date --date='"$((OFFSET))" days ago' +%Y%m%d"
DATEFULL=$(eval "$COMMAND")

echo offset $OFFSET
echo command $COMMAND
echo datefull $DATEFULL

Output

$ OFFSET=$(date +%u)
$ COMMAND="date --date='"$((OFFSET))" days ago' +%Y%m%d"
$ DATEFULL=$(eval "$COMMAND")
$ echo offset $OFFSET
offset 1
$ echo command $COMMAND
command date --date='1 days ago' +%Y%m%d
$ echo datefull $DATEFULL
datefull 20210822

Upvotes: 1

Related Questions