0

Got a bash script to create a backup of some files, it is set in Cron.

The bash command, including output, is:

[vagrant@localCentOS71 ~]$ sudo create_backup.sh
Check if all is good ...
done
Doing it ..
Backup file is: 1482419092_backup.tar ... Yeah!
done

How can I store 1482419092_backup.tar in a variable, for later use, in the same shell command.

The goal is to create a symlink to a folder of the just created backup file, in one shell command.

So far i've got:

create_backup.sh && ln -s $BACKUP_FILE /folder/here
  • 2
    making symlink in create_bash.sh would be easier and cleaner solution. – Ipor Sircer Dec 22 '16 at 15:17
  • What is create_backup.sh? Is that your script? Why don't you just modify it to print only the name to stdout? – terdon Dec 22 '16 at 15:24
  • Not my script. I know it's easier, but I can't configure it. – Kevin C Dec 22 '16 at 15:30
  • maybe create your own copy of it? – Jeff Schaller Dec 22 '16 at 17:03
1

It would be much simpler to just edit the script, but if that's not a possibility, you can do:

BACKUP_FILE=$(create_backup.sh | grep -oP 'Backup file is:\s*\K\S+') && 
ln -s $BACKUP_FILE /folder/here
0

Your shell script is executed by another shell which is a sub process.

There is no direct way to pass a variable from the child process to its parent.

One method could be to execute the script with your current shell with the dot (".") operator, but any call to exit will stop your current shell and you will inherit all the variables of your script :

. ./create_backup.sh && ln -s $BACKUP_FILE /folder/here

A better way is to use file to store your variable.

At some point in your script you save the value of the variable :

declare -p BACKUP_FILE > /tmp/somefile.sh

or :

echo BACKUP_FILE=\""$BACKUP_FILE"\" > /tmp/somefile.sh

Then you can execute :

if ./create_backup.sh
then . /tmp/somefile.sh
     ln -s $BACKUP_FILE /folder/here
fi

Another way without files, could be to read from the stdin of the script :

OUTSCRIPT=` ./create_backup.sh | grep 'BACKUP_FILE=' `

Here is an another solution : the parenthesis "()" creates a sub-shell to protect you from the exit calls and unwanted variables of the script AND you don't have to modify the script :

if ( . ./create_backup.sh && declare -p BACKUP_FILE > /tmp/somefile )
then . /tmp/somefile
     ln -s $BACKUP_FILE /folder/here
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.