jktstance
jktstance

Reputation: 165

Bash - running programs in background still causes script to wait

I wrote a simple wrapper script for my favorite editor, nedit. It will take a list of arguments and open all non-gzipped files in one window and it will take each gzipped file, zcat them to a temporary file, and open those in separate windows. However, running the nedit causes the script to wait until the window is closed, even if I use & or nohup. Am I missing something here?

#!/bin/bash

declare -a nongzipped
for file in $@; do
    if file $file | grep -q gzip; then
        timestamp=$(date +"%F_%T")
        tempfile="tmp_$timestamp"
        $( zcat $file > $tempfile )
        $( nedit -background lightskyblue3 $tempfile & )
        $( rm $tempfile )
    else
        nongzipped+=("$file")
    fi
done

if [ ${#nongzipped[@]} -ne 0 ]; then
    $( nedit ${nongzipped[@]} & )
fi

Upvotes: 0

Views: 128

Answers (2)

chepner
chepner

Reputation: 532268

The shell induced by the command substitution $(...) cannot exit until its background jobs complete. (Compare sleep & with $( sleep & ).) You don't need them anyway, so just remove them.

if file $file | grep -q gzip; then
    timestamp=$(date +"%F_%T")
    tempfile="tmp_$timestamp"
    zcat $file > $tempfile
    nedit -background lightskyblue3 $tempfile &
    rm $tempfile
else
    nongzipped+=("$file")
fi    

Upvotes: 4

ForceBru
ForceBru

Reputation: 44906

Do you really need $(command) here? This syntax is usually used to get the output of command and assign it to a variable. That's probably the reason your script has to wait.

You'd better call your program without any special syntax, just program arg1 arg2 &

Upvotes: 1

Related Questions