Use two variables in the output of a bash script

0

I'm doing a simple%% co to be able to do directory backups, but I want the resulting file name to be script .

I have the following code.

#!/bin/bash
clear
ls -d */
echo "Elige el directorio del cual hacer el backup (sin incluir el /)"
read directorio
echo "Realizando el backup de $directorio..."
tar -zcvf $(directorio)_$(date +%F).tar.gz $directorio

But this generates the file directorio_aaaa-mm-dd

    
asked by akko 21.06.2017 в 00:36
source

4 answers

6

You could try something like this:

#!/bin/bash

clear

ls -d */

echo "Elige el directorio del cual hacer el backup (sin incluir el /)"
read directorio

echo "Realizando el backup de $directorio..."
tar -zcvf $directorio"_"$(date +%F).tar.gz $directorio

The error you have in the program is in the last line.

When you do this:

$(directorio)_$(date +%F).tar.gz

By using the operator $() , you are indicating that what is inside the parentheses is a command , therefore he ignores this and omits it, which results in it being < strong> _aaaa-mm-dd .

Therefore.

The solution consists of two steps:

  • Call the variable in the appropriate way
  • Concatenate to the name of the directory the character _

How do we do it?

Like this:

$directorio"_"$(date +%F).tar.gz

What we indicate to the interpreter is that the name of the directory concatenates the character _ , it should be concatenated since if it were added without the quotes, like this:

$directorio_$(date +%F).tar.gz

The interpreter would look for the variable $directorio_ , which would leave the file with the name yyyy-mm-dd.tar.gz .

    
answered by 21.06.2017 в 00:56
2

Only comment that you should use the quotes to avoid surprises when the variable is expanded and have a directory name with spaces:

"${directorio}_$(date +%F).tar.gz"

I wanted to leave this as a comment but my score is not enough to leave comments, only answers.

And since I can only leave one answer, I make one more contribution that does not answer the question but is that seeing what you want to do I could not help thinking about using a select , this way you prevent someone from entering incorrectly the name of the Directory:

PS3="Elige el número del directorio del cual deseas hacer el backup: "
select dir in */; do
    if [[ -d "$dir" ]];then
        tar -zcvf "${dir%/}_$(date +%F).tar.gz" "$dir"
        break
    fi
    echo "Selección inválida"
done
    
answered by 22.06.2017 в 01:48
0

You can do it in the following way:

export FECHA=($(date +"%d-%m-%Y_%H:%M:%S") )
export NAME=Directorio_${FECHA}.backup
tar -zcvf $(NAME).tar.gz $directorio
    
answered by 22.10.2018 в 15:42
-1

The solution was quite simple. I only replaced $ (directory) with $ {directory} .

    
answered by 21.06.2017 в 01:35