#!/bin/sh# -e 如果命令带非0返回值,立即退出# -f 禁止带扩展名的路径set -ef
# $KSH_VERSION变量表示ksh的版本if test -n "$KSH_VERSION"; thenputs(){ print -r -- "$*"}elseputs(){printf'%s\n'"$*"}fiALLMATCHES=0
# 查找是否有选项-a# 如果有选项-a,打印所有匹配的命令,否则打印第一个匹配的命令while getopts a whichopts
do case"$whichopts" in
a)ALLMATCHES=1 ;;
?) puts "Usage: $0 [-a] args"; exit 2 ;;
esacdone# shift n 表示将原来的位置参数左移n位。# $OPTIND 代表下一个待处理的参数的索引shift$(($OPTIND-1))# $#标表示参数的个数if["$#" -eq 0 ]; thenALLRET=1
elseALLRET=0
ficase$PATH in
(*[!:]:)PATH="$PATH:" ;;
esac# $@代表输入的所有的命令行参数# $IFS表示bash内部的域分割符。默认值为空格# [-f "filename"] 判断是否是一个文件# [-x "filename"] 判断文件是否具有可执行权限# [-z "str"] 判断字符串长度是否为0#for PROGRAM in "$@"; doRET=1
IFS_SAVE="$IFS"IFS=:
# 该程序首先判断具有全部路径的命令是否存在,比如这样使用: which /usr/bin/ls# 如果当使用如下时: which ls 该程序将在系统$PATH的路径下寻找相应的程序。case$PROGRAM in
*/*)if[ -f "$PROGRAM"]&&[ -x "$PROGRAM"]; thenputs "$PROGRAM"RET=0
fi ;;
*)for ELEMENT in $PATH; do if[ -z "$ELEMENT"]; thenELEMENT=.
fi if[ -f "$ELEMENT/$PROGRAM"]&&[ -x "$ELEMENT/$PROGRAM"]; thenputs "$ELEMENT/$PROGRAM"RET=0
["$ALLMATCHES" -eq 1 ]||breakfi done ;;
esacIFS="$IFS_SAVE"if["$RET" -ne 0 ]; thenALLRET=1
fidoneexit"$ALLRET"
CentOS 中的which命令
环境
Linux 2.6.32-220.17.1.el6.x86_64 #1 SMP Wed May 16 00:01:37 BST 2012 x86_64 x86_64 x86_64 GNU/Linux
which - shows the full path of (shell) commands
Which takes one or more arguments. For each of its arguments it prints to stdout the full path of the executables that would have been executed when this argument had been entered at the shell prompt. It does this by searching for an executable or script in the directories listed in the environment variable PATH using the same algorithm as bash(1)
在CentOS下,which是c语言写的
1234567891011
[wanglong@wanglong ~]$ which -a which
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde' /usr/bin/which
/usr/bin/which
[wanglong@wanglong ~]$ file /usr/bin/which
/usr/bin/which: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped
[wanglong@wanglong ~]$ ldd /usr/bin/which
linux-vdso.so.1 => (0x00007fff74fff000) libc.so.6 => /lib64/libc.so.6 (0x0000003250400000) /lib64/ld-linux-x86-64.so.2 (0x0000003250000000)[wanglong@wanglong ~]$