Bash 中如何判断一个命令是否存在
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):文件描述符为 0,Unix 程序默认从 stdin 读取数据。
- 标准输出文件(stdout):文件描述符为 1,Unix 程序默认向 stdout 输出数据。
- 标准错误文件(stderr):文件描述符为 2,Unix 程序会向 stderr 写入错误信息。
常用重定向写法:
| 写法 | 说明 |
|---|---|
command > file | 将 stdout 重定向到 file |
command 2> file | 将 stderr 重定向到 file |
command < file | 将 stdin 重定向到 file |
command > file 2>&1 | 将 stdout 和 stderr 合并后重定向到 file |
command > file1 < file2 | 将 stdout 重定向到 file1,stdin 重定向到 file2 |
command 2>> file | 将 stderr 追加到 file 末尾 |
/dev/null 文件
如果希望执行某个命令,但又不希望在屏幕上显示输出结果,可以将输出重定向到 /dev/null:
command > /dev/null 2>&1
/dev/null 是一个特殊文件,写入它的内容会被直接丢弃。2>&1 表示把 stderr 也合并到 stdout 一起丢掉,屏蔽所有输出。