简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM