Bash functions to run/manage MySQL, Redis, Sidekiq, Rails server
Pretty nicely written! In fact, if you want to DRY this up, I'm pretty sure you could do it yourself if you seriously tried... But here you go anyway ;-)

Non-standard features

The function keyword is non-standard:


function rpid {
    pgrep -f "$1" 2&gt; /dev/null
}



Write it this way instead:

rpid() {
    pgrep -f "$1" 2&gt; /dev/null
}


DRY-ing up

You could write running in terms of rpid:

running() {
    rpid "$1" &gt; /dev/null
}

rpid() {
    pgrep -f "$1" 2&gt; /dev/null
}


This way, the pgrep logic is only in one place. If you need to change something, you could do it in one place. Just remember that the caller (running) expects the correct exit code of success / failure, and no output on stderr.



The start / stop / status commands have the common elements of checking if the process is running or not. You could create helper functions to reduce the duplication:

start() {
    procname=$1; shift
    name=$1; shift
    if ! running "$procname"; then
        "$@"
    else
        echo "$name already running"
    fi
}

stop() {
    procname=$1; shift
    name=$1; shift
    if running "$procname"; then
        "$@"
    else
        echo "$name not running"
    fi
}

status() {
    procname=$1
    name=$2
    if running "$procname"; then
        echo "$name running"
    else
        echo "$name not running"
    fi
}


Then you can simplify the MySQL functions using these helpers:

msta() {
    start mysql MySQL mysql.server start
}

msto() {
    stop mysql MySQL mysql.server stop
}

mstat() {
    status mysql MySQL
}


Similarly for redis:

redis_start() {
    redis-server ~/.redis/redis.conf
    until running redis; do
      sleep 1
    done
}

redis_stop() {
    kill $(rpid redis)
    while running redis; do
      sleep 1
    done
}

resta() {
    start redis "Redis daemon" redis_start
}

resto() {
    stop redis "Redis daemon" redis_stop
}

restat() {
    status redis "Redis daemon"
}


And I left the rest for you as exercise:


rastat can be simplified using status
krs can be simplified similar to the way I did redis above
You can leave reportkill as it is, as it's a different pattern from the others


There remains still some duplication in the start, stop, status helpers, but trying to reduce that might hurt readability. I think the current form is the "sweet spot", trying to optimize further will have diminishing returns.

shellcheck.net

This site is really awesome for checking your shell scripts for common mistakes:

http://www.shellcheck.net/#