Skip to content

Instantly share code, notes, and snippets.

@b-ggs
Forked from jimeh/stub.bash
Created February 20, 2018 07:09
Show Gist options
  • Save b-ggs/5065aa9935ea50accbe2cc58dca7e82f to your computer and use it in GitHub Desktop.
Save b-ggs/5065aa9935ea50accbe2cc58dca7e82f to your computer and use it in GitHub Desktop.
Shell script helpers to stub and restore bash shell functions/commands in tests.
# Stub commands printing it's name and arguments to STDOUT or STDERR.
stub() {
local cmd="$1"
if [ "$2" == "STDERR" ]; then local redirect=" 1>&2"; fi
if [[ "$(type "$cmd" | head -1)" == *"is a function" ]]; then
local source="$(type "$cmd" | tail -n +2)"
source="${source/$cmd/original_${cmd}}"
eval "$source"
fi
eval "$(echo -e "${1}() {\n echo \"$1 stub: \$@\"$redirect\n}")"
}
# Restore the original command/function that was stubbed with stub.
restore() {
local cmd="$1"
unset -f "$cmd"
if type "original_${cmd}" &>/dev/null; then
if [[ "$(type "original_${cmd}" | head -1)" == *"is a function" ]]; then
local source="$(type "original_$cmd" | tail -n +2)"
source="${source/original_${cmd}/$cmd}"
eval "$source"
unset -f "original_${cmd}"
fi
fi
}

stub.sh Example Usage

test.sh:

#! /usr/bin/env bash
source "stub.bash"
    
type htop
stub htop
type htop
restore htop
type htop

Running it:

$ ./test.sh
htop is /usr/local/bin/htop
htop is a function
htop ()
{
    echo "htop stub: $@"
}
htop is /usr/local/bin/htop

test2.sh:

#! /usr/bin/env bash
source "stub.bash"

my_name() {
  echo "my name is $@"
}

type my_name
stub my_name
type my_name
restore my_name
type my_name

Running it:

$ ./test2.sh
my_name is a function
my_name ()
{
    echo "my name is $@"
}
my_name is a function
my_name ()
{
    echo "my_name stub: $@"
}
my_name is a function
my_name ()
{
    echo "my name is $@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment