Search code examples
bashpipetemporary-fileszenity

How can I avoid using a temporary file in this bash script?


As a beginner with shell scripting, I've written this bash script function to return the md5sum of a file, while providing the user with a GUI progress bar.

md5sum_of_file () {
    (pv -n $1 | md5sum | sed -e 's/\s.*//g' > /tmp/md5sum) 2>&1 | zenity --progress --auto-close
    echo $(</tmp/md5sum)
    rm /tmp/md5sum
}

pv -n $1 feeds the file into md5sum | sed -e 's/\s.*//g' (sed strips the output of the sum's associated filename), while piping a percentage to zenity --progress --auto-close.

I know you can't simply assign the checksum to a variable in this instance, as "(pv -n $1 | $(md5sum | sed -e 's/\s.*//g'))" is within its own subshell. But is there a way to do this without creating a temporary file (in this case "/tmp/md5sum")?

Thanks.


Solution

  • The only thing that zenity is using is the standard error from pv, so use a process substitution to do that without involving any stdout or stderr from the other commands. This lets the output of sed simply go to standard output without the need for any temp files.

    pv -n "$1" 2> >(zenity --progress --auto-close) | md5sum | sed -e 's/\s.*//g'