4

I can't remember how to capture the result of an execution into a variable in a bash script.

Basically I have a folder full of backup files of the following format: backup--my.hostname.com--1309565.tar.gz

I want to loop over a list of all files and pull the numeric part out of the filename and do something with it, so I'm doing this so far:

HOSTNAME=`hostname`
DIR="/backups/"
SUFFIX=".tar.gz"
PREFIX="backup--$HOSTNAME--"
TESTNUMBER=9999999999


#move into the backup dir
cd $DIR

#get a list of all backup files in there
FILES=$PREFIX*$SUFFIX

#Loop over the list
for F in $FILES
do
    #rip the number from the filename
    NUMBER=$F | sed s/$PREFIX//g | sed s/$SUFFIX//g

   #compare the number with another number

   if [ $NUMBER -lg $TESTNUMBER ]
      #do something

   fi

done

I know the "$F | sed s/$PREFIX//g | sed s/$SUFFIX//g" part rips the number correctly (though I appreciate there might be a better way of doing this), but I just can't remember how to get that result into NUMBER so I can reuse it in the if statement below.

2 Answers 2

5

Use the $(...) syntax (or ``).

NUMBER=$( echo $F | sed s/$PREFIX//g | sed s/$SUFFIX//g )

or

NUMBER=` echo $F | sed s/$PREFIX//g | sed s/$SUFFIX//g `

(I prefer the first one, since it is easier to see when multiple ones nest.)

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

5 Comments

The only problem I ever have with the $(...) style, is that these days, I think I'm looking at jQuery. ;-)
That's what I tried initially (without the cat) but this doesn't seem to do the job. Rather than capturing the number i.e. the result of the filename passed through sed a couple of times) it seems to return the whole filename...
About cat, this should of course be echo. I did not fully read the question ...
@Orbling: The problem with the `` style is that it conflicts with the inline highlighting on Stack Overflow :-p
Nice one Paŭlo thanks! Any other day of the week and I'd have realised that's what I was missing too :)
0

Backticks if you want to be portable to older shells (sh):

NUMBER=`$F | sed s/$PREFIX//g | sed s/$SUFFIX//g`.

Otherwise, use NUMBER=$($F | sed s/$PREFIX//g | sed s/$SUFFIX//g). It's better and supports nesting more readily.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.