Skip to content

Instantly share code, notes, and snippets.

@jimeh
Last active February 16, 2022 23:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jimeh/5886795 to your computer and use it in GitHub Desktop.
Save jimeh/5886795 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