Skip to content

Instantly share code, notes, and snippets.

@yosugi
Last active September 19, 2019 01:57
Show Gist options
  • Select an option

  • Save yosugi/986d3240cdd732b3c45396921cfd9039 to your computer and use it in GitHub Desktop.

Select an option

Save yosugi/986d3240cdd732b3c45396921cfd9039 to your computer and use it in GitHub Desktop.
Add custom subcommand into any command
#!/bin/zsh
#
# with-subcommand.zsh
#
# Description:
#
# Add custom subcomand into any command
#
# Installation:
#
# $ git clone https://github.com/yosugi/with-subcommand.zsh
# $ cp with-subcommand.zsh/with-subcommand.zsh ~/.with-subcommand.zsh
# $ echo '[ -f ~/.with-subcommand.zsh ] && source ~/.with-subcommand.zsh' >> ~/.zshrc
# $ source ~/.zshrc
#
# Usage:
#
# * install & load with-subcommand.zsh
# * define subcommand in .zshrc
# * if you want to add `tmux args` command, define `tmux-args` function, alias, or command.
# * see below example
#
# Example:
#
# If you want to add `tmux args` subcommand,
# Write below script your .zshrc
#
# ```
# [ -f ~/.with-subcommand.zsh ] && source ~/.with-subcommand.zsh
# alias tmux='(){ with-subcommand tmux "$@" }'
# function tmux-args() {
# echo "args:" "$@"
# }
# ```
#
# You can use tmux subcommand "tmux args".
#
# ```
# $ tmux args 1 2 3
kj# args: 1 2 3
# ```
#
# You can use original tmux subcomannd too.
#
# ```
# $ tmux ls
# develop: 4 windows (created Thu Mar 21 18:35:49 2018) [136x65] (attached)
# ```
#
# Version: 0.1.0
# Author : yosugi
# License: MIT
function with-subcommand() {
local args
local subcommand
subcommand="$1-$2"
if type "$subcommand" >/dev/null 2>&1; then
args=("${@:3}")
eval "$subcommand" "${args[*]}"
return $?
fi
args=("${@:2}")
eval \\"$1" "$args[*]"
return $?
}
# example
# alias tmux='(){ with-subcommand tmux "$@" }'
# function tmux-args() {
# echo "args:" "$@"
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment