Sunday, March 24, 2013

The Dialog Command

Geek speak alert....

A while back I said something about using this blog as a place for some notes (I'm unlikely to lose my blog....). So here goes. Dialog is this brilliant tool for making your bash scripts look... well... just a little more friendly. It's got a few oddities though. For example, responses are sent to stderr. The only examples I could find to make this work was to make a file in temp that contains responses and then read that back in. So it looks something along the lines of:

 dialog --title "A title" --menu "Some text" 20 50 20 \  
  "1" "Option 1" \  
  "2" "Option 2" \  
 case $ANSWER in  
  "1") echo "Option 1 was selected" ;;  
  "2") echo "Option 2 was selected" ;;  

I wanted to do something a little different. I wanted to show the progress of copying files - to copy a usb stick. The information I found on the Internet for doing this was around doing a file count. I have one file that's a couple of GB's big though while the rest of the files are small. In which case, it just wouldn't give me the information I need. Or at least, not a meaningful representation. So... given that I didn't really care too much about accuracy but wanted an indication for how long times were going to take, I came up with the following:

 SOURCE_SIZE=$( du -c $SOURCE | tail -n1 | cut -f1 )  
 cp $SOURCE/* $DEST & CP_PID=$!  
  while [ -d "/proc/$CP_PID" ] ; do  
   PERCENTAGE=$( echo "scale=2 ; $( du -c $DEST | tail -n1 | cut -f1 ) / $SOURCE_SIZE * 100" | bc " cut -f1 -d "." )  
   sleep 1  
   echo -e "$PERCENTAGE\n###\n$PERCENTAGE %\n###"  
 ) | dialog --title "Copy Progress" --gauge "" 6 50 6  

So it relies on the du command. There are probably ways of making this a little more accurate (though I'm not sure I care). Perhaps using apparent size for the du commands?

Anyway... the whole point of this post... Given that I wasn't able to find the information I wanted and had to hack it together myself, hopefully putting this information here will help someone with similar needs.

No comments:

Post a Comment