Can I alias a subcommand? (shortening the output of `docker ps`)

后端 未结 3 789
别那么骄傲
别那么骄傲 2020-11-27 20:52

The docker command has a ps sub-command that emits very long lines:

$ docker ps -a
CONTAINER ID        IMAGE                                


        
3条回答
  •  情话喂你
    2020-11-27 20:57

    You can wrap docker in a function that checks for the specific subcommand and passes everything else through. (The below will actually work with not just zsh, but any POSIX-compliant shell -- a category to which zsh doesn't quite belong).

    docker() {
      case $1 in
        ps)
          shift
          command docker ps --format 'table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}' "$@"
          ;;
        *)
          command docker "$@";;
      esac
    }
    

    If you wanted a more generic wrapper function (that doesn't need to know about your specific desired ps logic), that could be done as follows (note that this version is not compatible with baseline POSIX sh due to its use of local; however, this is an extension implemented even by ash and its derivatives):

    docker() {
      local cmd=$1; shift
      if command -v "docker_$cmd" >/dev/null 2>/dev/null; then
        "docker_$cmd" "$@"
      else
        command docker "$cmd" "$@"
      fi
    }
    

    ...after which any subcommand can have its own functions defined, without the wrapper needing to be modified to know about them (you could also create a script in the PATH named docker_ps, or provide the command in any other manner you choose):

    docker_ps() {
      command docker ps --format 'table {{.Image}}\t{{.Names}}\t{{.Ports}}\t{{.Status}}' "$@"
    }
    

提交回复
热议问题