0

I am trying to create a quick script that will get a file from a backup folder. The backup file is generated every day and have the filename format of:

backup-sql-YYYYMMDD.zip

I am trying to get the filename by using:

#!/bin/sh

VAR_1="backup-sql-"
VAR_2=date +%Y%m%d
VAR_3=$VAR_1$VAR_2

echo "$VAR_3"

However the output is:

backup-sql-

When I run:

date +%Y%m%d

I get

20180704    

So I am not sure why this is happening. Please can someone help me :)

PesaThe
  • 7,259
  • 1
  • 19
  • 43
modusTollens
  • 397
  • 7
  • 23
  • 1
    You are missing command substitution. Paste your code to [shellcheck.net](https://www.shellcheck.net/). – PesaThe Jul 04 '18 at 10:33
  • 1
    Your shell must be broken since it's not giving you a syntax error on `VAR_2=date +%Y%m%d` (assuming you'd have acted on it or at the very least told us about it if you were getting a syntax error). – Ed Morton Jul 04 '18 at 12:23
  • @PesaThe Thank you - that helped and is a great tool. +1 – modusTollens Jul 04 '18 at 13:07
  • @EdMorton Thanks for the reply, I solved it with the answer below by adding `$()` – modusTollens Jul 04 '18 at 13:08
  • Possible duplicate of [How to set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-of-a-command-in-bash) – Benjamin W. Jul 04 '18 at 13:27

2 Answers2

1

You should be using backticks to capture the output of the date command and assign it to a shell variable.

VAR2=`date "+%Y%m%d"`

In case you want to make sure the variable value is passed on to subsequent child processes you may want to export it as:

export VAR2=`date "+%Y%m%d"`
asatsi
  • 452
  • 2
  • 5
  • No you should not be using backticks. See https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html – Ed Morton Jul 04 '18 at 12:24
1

You could use:

$(command)

or

`command`

From your example give a try to:

VAR_2=$(date +%Y%m%d)

Check Command Substitution for more details:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ‘$’, ‘`’, or ‘\’. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

nbari
  • 25,603
  • 10
  • 76
  • 131