Search code examples
ruby-on-railslinuxbashterminallinux-mint

Play sound on terminal output


Is there any way to play a sound when a program outputs something to a terminal?

Let's say I run:

$ for i in {0..10}; do echo $i; done

Can I play a sound, or run any command, on every newline printed?

More specifically, I'm running WEBrick for Rails development and I'd like to know whenever there's a request to the server without having to look at it.

(I'm using Bash on Linux Mint 17)


Solution

  • This might be a pretty complex solution, but it does what I need.

    In my .bashrc file, I added the following:

    #ensure that the call is made only once, preventing an infinite loop
    
    if [ $SHLVL == 1 ]
    then
        script -afq ~/custom/log.txt #log everything that happens in the shell
    fi
    
    #call my script only once by checking for another instance of it
    
    if [[ ! $(pidof -x script.sh) ]]
    then
        ~/custom/script.sh&
    fi
    

    My script.sh file checks for changes in log.txt and plays a beep sound (you need to download it) when that happens:

    #!/bin/bash
    
    $(stat -c %y ~/custom/log.txt > ~/custom/update.txt)
    
    while :
    do
        now=$(stat -c %y ~/custom/log.txt)
        update=$(cat ~/custom/update.txt)
        if [ "$now" != "$update" ]
        then
            $(stat -c %y ~/custom/log.txt > ~/custom/update.txt)
            $(play -q ~/custom/beep.ogg vol 0.1) #props to franklin
        fi
    done
    

    This will make it so that everytime something changes in the shell, including typing, script.sh will run play. Now I get to know whenever there is a request to my WEBrick server without having to look at the terminal.