How can I get the output of a command to a bash variable?

I don’t remember how to write the result of execution to 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 iterate over the list of all files and extract the numerical part from the file name and do something with it, so I still do this:

 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 that the "$F | sed s/$PREFIX//g | sed s/$SUFFIX//g" correctly copies the number (although I understand that there may be a better way to do this), but I just can’t remember how to get this result in NUMBER so that I can reuse it in if below instruction.

+4
source share
2 answers

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, as it’s easier to see when several nest.)

+5
source

Backticks if you want to be portable for old 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 is better and maintains nesting more easily.

0
source

All Articles