data in formato YYYY-MM-DD in uno script di shell

Ho provato ad usare $(date) nel mio script bash shell, tuttavia voglio la data nel formato YYYY-MM-DD. Come posso ottenerlo?

Soluzione

In bash (=4.2) è preferibile usare il formattatore di date integrato in printf (parte di bash) piuttosto che l'esterno date (solitamente GNU date).

Come tale:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal

In bash (

Commentari (15)

Prova: $(data +%F)

Commentari (1)

Si può fare qualcosa del genere:

$ date +'%Y-%m-%d'
Commentari (0)