
12

检查linux命令是否存在的正确方式
source link: https://www.lujun9972.win/blog/2017/03/20/%E6%A3%80%E6%9F%A5linux%E5%91%BD%E4%BB%A4%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8%E7%9A%84%E6%AD%A3%E7%A1%AE%E6%96%B9%E5%BC%8F/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

检查linux命令是否存在的正确方式
之前我一直是在用 which
来判断linux命令是否存在的,但是它并不能用来检查内置命令和函数是否存在.
command_exists() { which "$@" > /dev/null 2>&1 } command_exists ls echo "检查外部命令:" $? function t () { echo "I am a function" } command_exists t echo "检查函数:" $? command_exists cd echo "检查内置命令:" $? command_exists sldj echo "检查没有的命令:" $?
检查外部命令: 0 检查函数: 1 检查内置命令: 1 检查没有的命令: 1
直到今天看了下daocloud提供的配置docker加速器脚本(https://get.daocloud.io/daotools/set_mirror.sh).
这个脚本里面也实现了一个 command_exists
函数,不过是使用bash内建的 command
命令来实现的.
command_exists() { command -v "$@" > /dev/null 2>&1 }
使用 command -v
检查命令时,当命令是已定义的函数,内建命令或者 PATH
中能找到的外部命令时都,返回值都是0,否则会返回1.
command_exists() { command -v "$@" > /dev/null 2>&1 } command_exists ls echo "检查外部命令:" $? function t () { echo "I am a function" } command_exists t echo "检查函数:" $? command_exists cd echo "检查内置命令:" $? command_exists sldj echo "检查没有的命令:" $?
检查外部命令: 0 检查函数: 0 检查内置命令: 0 检查没有的命令: 1
这确实比用 which
要更好用.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK