Shell 脚本判断命令是否存在

10 min read

command 命令

#! /bin/bash
if command -v git >/dev/null 2>&1; then 
  echo 'exists git' 
else 
  echo 'no exists git' 
fi

type命令

#! /bin/bash
if type git >/dev/null 2>&1; then 
  echo 'exists git' 
else 
  echo 'no exists git' 
fi

重定向

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准 输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
  • 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

默认情况下
command > file 将 stdout 重定向到 file
command 2 > file 将 stderr 重定向到 file
command < file 将stdin 重定向到 file。
command > file 2>&1 将 stderr 和 stdout合并后重定向到 file
command > file1 < file2 将 stdout 重定向到 file1,stdin 重定向file2
command 2 >> file将 stderr 追加到 file末尾

/dev/null 文件

如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null
command > /dev/null 2>&1屏蔽 stdout 和 stderr