命令 -v 自定义输出

命令 -v 自定义输出

我目前有以下命令:

command -v gpg 2>/dev/null || { echo "Cound not find gpg. Aborting."; }

我不想将输出重定向到 /dev/null,而是想显示一条消息,说明命令的输出和后续内容found!

IE

  • 如果找不到 gpg:Cound not find gpg. Aborting.
  • 如果找到 gpg:gpg found at /usr/local/bin/gpg

答案1

最简单的方法是这样的:

command -v gpg &>/dev/null && 
    echo "gpg found at  $(command -v gpg)" || 
    echo "Cound not find gpg. Aborting."

当然,这不是很优雅,因为它需要运行command两次。另一种方法是:

gpg=$(command -v gpg 2>/dev/null) && 
    echo "gpg found at $gpg." ||
    echo "Cound not find gpg. Aborting."

答案2

这会起到作用:

command -v gpg &>/dev/null && echo "gpg has been found at $(which gpg)" || 
{ echo "Cound not find gpg. Aborting."; }

答案3

别名可能会隐藏可执行文件的路径,如果您只关心路径,您可以执行以下操作:

cmd_exists() {
  (
    unalias "$1" 2>/dev/null
    _status=$(command -v "$1")
    case $_status in
      *"$1") echo "$1 found at $_status";;
      "") echo "Could not find $1. Aborting."; return 127;;
    esac
  )
}

cmd_exists gpg

相关内容