Last Updated: February 25, 2016
·
546
· nmichel

Sequentially executing the same command with various operations

Fed up with repetitive command invocations as in

$> ./rebar get-deps && ./rebar clean && ./rebar compile

I propose a simple shell script to rewrite this kind of stuff as

$> seq ./rebar get-deps clean compile

Form

seq [-s | --silent] [-se | --silent-error] [-E | --stop-on-error] command op1 op2 ...

Options

  • -s |--silent

Command output is dumped

  • -se |--silent-error

Do not warn on failing operations

  • -E |--stop-on-error

Stop on the first failing operation

Examples

$> ../bin/seq.sh  -s -se  -E ./rebar get-deps foo clean bar compile
$> ../bin/seq.sh  -s   -E ./rebar get-deps foo clean bar compile
operation foo failed

The script

#!/bin/bash

function usage() {
    echo `basename $0` "[-s | --silent] [-se | --silent-error] [-E | --stop-on-error] command op1 op2 ..."
}

silentCommand=false
stopOnError=false
silentError=false

continue=true
options=""
while [ "$continue" == true ]; do
    case $1 in
        -s | --silent)
            shift
            silentCommand=true
            options="$options --silent"
            ;;
        -se | --silent-error)
            shift
            silentError=true
            options="$options --silent-error"
            ;;
        -E | --stop-on-error)
            shift
            stopOnError=true
            options="$options --stop-on-error"
            ;;
        *)
            continue=false
    esac
done

if [ $# -lt 2 ]
then
    usage
    exit
fi

self=$0
cmd=$1
op=$2

redirect="2>&1"
if [ $silentCommand == true ]
then
    redirect="$redirect > /dev/null"
fi

eval "$cmd $op $redirect"

if [ ! $? -eq 0 ]
then
    if [ $silentError == false ]
    then
        echo "operation $op failed" 
    fi

    if [ $stopOnError == true ]
    then
        exit
    fi
fi

shift; shift;
if [ $# -ge 1 ]
then
    $self $options $cmd $*
fi