Using "watch" to run a function repeatedly in Bash?

I have multiple aliases and functions that used to not work with watch until I created a function that wraps the watch command like this, inspired from @l'L'l accepted answer:

# fishshell
function watch
    command watch -n 0.2 -x fish -c "$argv"
end

# bash
function watch() {
    watch -n 0.2 -x bash -c "$@"
}

# zsh
watch() {
    watch -n 0.2 -x zsh -c "$@"

}

The only inconvenient I see here is that you can't pass more watch arguments if you want to, for sure me I added the -n 0.2 flag to make it refresh every 0.2 seconds, if you have other flags that you like to add you will need to add them here beforehand.

Personally I only use fishshell so I hope the others are not broken, don't hesitate to edit the answer to fix the commands!

Also as a bonus for the lazy that often use watch: alias w=watch


It's possible that watch is not aware of your connection_test_loop function. You can try adding an export below the test_connection to perhaps solve the issue:

test_connection
export -f connection_test_loop
...

↳ http://linuxcommand.org/lc3_man_pages/exporth.html

When calling watch, you may need this syntax:

watch -x bash -c connection_test_loop