You must be scratching your head and wondering what this post is about, if you know about zcat or zgrep, you would soon understand.

I have a habit to download whatever stuff into /tmp which is a tmpfs. But oftentimes, I forget to switch to it before issuing an command. To deal with it, a couple of command has been modified, either by alias or whatever measure to ensure I don’t have to manually switch to.

Even so, the most command downloaders, wget and curl still don’t get such automatic treatment, and I sometimes asked why I’ve forgot again and again, over and over. So here are my:

1   command_not_found_handle

The first one is the original which I thought is great, but it has a huge caveat.


##################################
# make sure we do commands in /tmp

# Caveat:
# the shell would not stay in /tmp, but the commands does run in /tmp.

command_not_found_handle() {
local cmd tcmd

cmd="$1"
tcmd="${1#t}"
shift

if [[ $cmd == t$tcmd ]]; then
if
type $tcmd &>/dev/null; then
cd /tmp
$tcmd "$@"
return
fi
cmd="$tcmd for t$tcmd"
fi

echo "bash: $cmd: command not found" >&2
return 127
}

It utilizes Bash’s special command_not_found_handle function1, once you define it, Bash will hand over the error handling once a command isn’t found. With it, this code can try to invoke foobar arg1 arg2 if you try to execute:


$ tfoobar arg1 arg2

If foobar doesn’t exist, you get a similar error message:


bash: foobar for tfoobar: command not found

If the command doesn’t fall into t<foobar> pattern, then the error message would look like the typical command not found message with same exit status code.

The problem with this approach is, even the command is executed in /tmp, the user wouldn’t get to switch to it.

2   alias

I was wondering how can I deal with the issue, and it turned out that a simple alias would do wonderfully:


alias tmp='cd /tmp;'

You just run like:


$ tmp tfoobar arg1 arg2

I like the zgrep-like style, t<foobar> would be slinkier. Aliasing would require a space to separate, but this is the best and simplest option I could come up with. Granted, this is not wrapper in any sense of wrapping, not by my definition, anyway.

3   Conclusion

There must be some other solutions to my problem, such as using a wrapper script to be symbolic linked or use special functions, but they all have to be manually created for each command to be shadowed. I want to have a lazy way and it works generally and universally without additional steps.

I’d really link the symlink approach, because you can check what links to the wrapper script. A few months ago, I got an idea of embedding parameter in linking file name. It’s an interesting idea, nevertheless, it would still suffer the issue of not switching in the invoking shell.

So alias is the best one for me


[1]I first discovered such function hook when I was writing script called mean.bash, didn’t end up using it in the end.