0

Apologies if the title isn't worded very well, hard to explain exactly what I'm trying to do without an example

I am running a database backup command that creates a file with a timestamp. In the same command I am then uploading that file to a remote location.

pg_dump -U postgres -W -F t db > $backup_dir/db_backup_$(date +%Y-%m-%d-%H.%M.%S).tar && gsutil cp $backup_dir/db_backup_$(date +%Y-%m-%d-%H.%M.%S).tar $bucket_dir

As you can see here it is creating the timestamp during the pg_dump command. However in the 2nd half of the command, the timestamp will now be different and it won't find the file.

I'm looking for a way to 'save' or assign the value of the backup file name from the first half of the command, so that I can then use it in the 2nd half of the command.

Ideally this would be done across 2 separate commands however in this particular use case I'm limited to 1.

Shox2711
  • 139
  • 1
  • 12
  • 1
    Just store the output of the `date` in a variable, before calling your command: `now=$(date +%Y-%m-%d-%H.%M.%S)` and use `$now` instead of `$(date ...)` in your command. – M. Nejat Aydin Sep 11 '20 at 08:55
  • 2
    if one command is important may be done using following parameter expansion if `now` is not set before `${now:=$(date ..)}`, howover as it is already a list command , just `now=$(date ..) && ...`, as @M.NejatAydin said – Nahuel Fouilleul Sep 11 '20 at 08:59
  • You can also try `pgdump .... -f ${...}` (see: --file -f https://www.postgresql.org/docs/9.3/app-pgdump.html) and `&& ... cp $_ ...` where `$_` refers the last argument of last command executed, see: https://stackoverflow.com/questions/3371294/how-can-i-recall-the-argument-of-the-previous-bash-command But there is no reason to make it so shiny (if it works), keep it simple and readable, you already list commands, it is not one command, so just assign the date at the beginning and reuse it. – thanasisp Sep 11 '20 at 09:30
  • It seems unlikely you are limited to one command if you can use `&&`. That is combining two separate commands - why not just `now=$(date +%Y-%m-%d-%H.%M.%S) && ...` ? – jeremysprofile Sep 11 '20 at 15:13

1 Answers1

1

a variation of the advice already given in comments -

fn=db_backup_$(date +%Y-%m-%d-%H.%M.%S).tar           &&
   pg_dump -U postgres -W -F t db > "$backup_dir/$fn" &&
   gsutil cp "$backup_dir/$fn" "$bucket_dir"

The $fn var makes the whole thing shorter and more readable, too.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36