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 :)

5
  • 1
    You are missing command substitution. Paste your code to shellcheck.net. Commented Jul 4, 2018 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). Commented Jul 4, 2018 at 12:23
  • @PesaThe Thank you - that helped and is a great tool. +1 Commented Jul 4, 2018 at 13:07
  • @EdMorton Thanks for the reply, I solved it with the answer below by adding $() Commented Jul 4, 2018 at 13:08
  • Possible duplicate of How to set a variable to the output of a command in Bash? Commented Jul 4, 2018 at 13:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"` 

1 Comment

No you should not be using backticks. See gnu.org/software/bash/manual/html_node/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.