I'd like to ask if there is a way to add a prefix before certain command. Most of the similar questions on SO regard adding prefix to the output of the command and not to the command execution itself so here is my example:
I need to connect to docker container, I'm working on Windows and use ConEmu with bash terminal so I need to use winpty prefix to be able to connect to unix terminal of the container as follows:
docker exec -it my_container bash
results in:
unable to setup input stream: unable to set IO streams as raw terminal: The handle is invalid.
so I need to use:
winpty docker exec -it my_container bash
root@0991eb946acc:/var/www/my_container#
Unfortunately If I add from the begging winpty my auto completion doesn't work so I need to firstly write docker command and then jump to beginning of command to input winpty. I'd like to have bash automatically detect whenever I run "docker exec" to add winpty prefix before it. How to achieve that? I know I could make an alias for
alias de='winpty docker exec'
but I would rather stay with normal docker command flow to have the autocompletion.
Write a shell function that wraps docker. If it's a docker exec command call winpty, otherwise use command to fall back to the underlying docker binary.
docker() {
if [[ ${1:-} == exec ]]; then
(set -x; winpty docker "$@")
else
command docker "$@"
fi
}
I put the set -x in there so it'll print when winpty is being invoked, that way there's no hidden magic. I like to be reminded when my shell is doing sneaky things.
$ docker exec -it my_container bash
+ winpty docker exec -it my_container bash
root@0991eb946acc:/var/www/my_container#
I'm not familiar with winpty but I expect winpty docker will call the docker binary and not this shell function. But if I'm wrong you're in trouble cause it'll the function will call itself over and over in an endless recursive loop. Yikes! If that happens you can use which to ensure it calls the binary.
docker() {
if [[ ${1:-} == exec ]]; then
(set -x; winpty "$(which docker)" "$@")
else
command docker "$@"
fi
}
If you're wondering about the shell syntax:
${1} is the function's first argument.${1:-} ensures you don't get an "unbound variable" error on the off-chance that you have set -u enabled to detect unset variables."$@" is an array of all the function's arguments.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With