美文网首页
Bash中如何判断一个命令是否存在

Bash中如何判断一个命令是否存在

作者: 乔伯 | 来源:发表于2015-09-16 16:01 被阅读4313次

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

hash命令

#! /bin/bash
if hash git 2>/dev/null; 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

参考:

http://c.biancheng.net/cpp/view/2738.html

相关文章

网友评论

      本文标题:Bash中如何判断一个命令是否存在

      本文链接:https://www.haomeiwen.com/subject/gpkbcttx.html