LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash background (&) with control operators (&&) (http://www.linuxquestions.org/questions/programming-9/bash-background-and-with-control-operators-and-and-703932/)

int0x80 02-11-2009 01:35 PM

Bash background (&) with control operators (&&)
 
I have a set of files to copy and decompress, and want to do these operations concurrently with a script.

Manually it would be something like:

Code:

cp /src/file1.gz /dest/ & && gzip -d /dest/file1.gz &
cp /src/file2.gz /dest/ & && gzip -d /dest/file2.gz &
cp /src/file3.gz /dest/ & && gzip -d /dest/file3.gz &

The single & is intended to background the processes, while the && is intended to execute the gzip process if and only if the cp completes successfully.

My script is:

Code:

#!/bin/bash
FILES="*file$(date +"%m%d")*.gz"
DIR_SRC="/src"
DIR_DEST="/dest"

if [ -d $DIR_SRC ]; then
    for f in $(ls $DIR_SRC/$FILES); do
        logger -s "cp_incoming.sh: processing $f";
        cp $f $DIR_DEST & && gzip -d $DIR_DEST/$(basename $f) &;
    done
else
    logger -s "cp_incoming.sh: $DIR_SRC was not found - exiting"
    exit 1
fi

exit 0

When I run it, bash gets angry with the following error:

Code:

$ ./cp_incoming.sh
./cp_incoming.sh: line 9: syntax error near unexpected token `&&'
./cp_incoming.sh: line 9: `        cp $f $DIR_DEST & && gzip -d $DIR_DEST/$(basename $f) &; '

So what is the proper syntax to accomplish this?

TIA

int0x80 02-11-2009 01:54 PM

Figured it out:

Code:

#!/bin/bash
FILES="*file$(date +"%m%d")*.gz"
DIR_SRC="/src"
DIR_DEST="/dest"

if [ -d $DIR_SRC ]; then
    for f in $(ls $DIR_SRC/$FILES); do
        logger -s "cp_incoming.sh: processing $f"
        cp $f $DIR_DEST && gzip -d $DIR_DEST/$(basename $f) &
    done
else
    logger -s "cp_incoming.sh: $DIR_SRC was not found - exiting"
    exit 1
fi

exit 0

I just needed to treat the whole cp && gzip operation as one process to be backgrounded. Removing the semicolons at the end of the lines int he for loop also helped.


All times are GMT -5. The time now is 03:57 AM.