如果内置命令,则检入bash和csh

时间:2011-09-13 09:37:24

标签: bash shell csh

如果内置命令,我如何检查bash和csh?有没有与大多数贝壳兼容的方法?

5 个答案:

答案 0 :(得分:12)

您可以尝试在csh中使用which或在bash中使用type。如果有东西是内置命令,它就会说出来;否则,您将获得PATH中命令的位置。

在csh中:

# which echo
echo: shell built-in command.

# which parted
/sbin/parted

在bash中:

# type echo
echo is a shell builtin

# type parted
parted is /sbin/parted

type也可能显示如下内容:

# type clear
clear is hashed (/usr/bin/clear)

...这意味着它不是内置的,但是bash已将其位置存储在哈希表中以加快对它的访问; {em>(一点点)更多this post on Unix & Linux

答案 1 :(得分:10)

在bash中,您可以使用type命令和-t选项。完整的详细信息可以在bash-builtins手册页中找到,但相关位是:

  

输入 -t name

     

如果使用-t选项,则键入打印的字符串为aliaskeywordfunctionbuiltin或{{1如果name分别是别名,shell保留字,函数,内置文件或磁盘文件。如果找不到名称,则不打印任何内容,并返回退出状态false。

因此您可以使用支票,例如:

file

会产生输出:

if [[ "$(type -t read)" == "builtin" ]] ; then echo read ; fi
if [[ "$(type -t cd)"   == "builtin" ]] ; then echo cd   ; fi
if [[ "$(type -t ls)"   == "builtin" ]] ; then echo ls   ; fi

答案 2 :(得分:4)

对于bash,请使用type command

答案 3 :(得分:2)

对于csh,您可以使用:

which command-name

如果它是内置的,它会告诉你。 不确定它对bash是否有效。 不过,我们小心别名。可能有选择。

答案 4 :(得分:1)

这里的其他答案很接近,但是如果别名或功能与您要检查的命令同名,则它们都会失败。

这是我的解决方案:

tcsh

使用where命令,该命令会显示所有命令名称,包括它是否为内置命令。然后grep查看其中一行是否表明它是内置的。

alias isbuiltin 'test \!:1 != "builtin" && where \!:1 | egrep "built-?in" > /dev/null || echo \!:1" is not a built-in"'

bash / zsh

使用type -a,它会显示所有命令名称,包括它是否为内置命令。然后grep查看其中一行是否表明它是内置的。

isbuiltin() {
  if [[ $# -ne 1 ]]; then
    echo "Usage: $0 command"
    return 1
  fi
  cmd=$1
  if ! type -a $cmd 2> /dev/null | egrep '\<built-?in\>' > /dev/null
  then
    printf "$cmd is not a built-in\n" >&2
    return 1
  fi
  return 0
}

ksh88 / ksh93

打开子shell,以便删除任何名称相同的别名或命令名称。然后在子shell中,使用whence -v。此解决方案中还有一些额外的古老语法支持ksh88

isbuiltin() {
  if [[ $# -ne 1 ]]; then
    echo "Usage: $0 command"
    return 1
  fi
  cmd=$1
  if (
       #Open a subshell so that aliases and functions can be safely removed,
       #  allowing `whence -v` to see the built-in command if there is one.
       unalias "$cmd";
       if [[ "$cmd" != '.' ]] && typeset -f | egrep "^(function *$cmd|$cmd\(\))" > /dev/null 2>&1
       then
         #Remove the function iff it exists.
         #Since `unset` is a special built-in, the subshell dies if it fails
         unset -f "$cmd";
       fi
       PATH='/no';
       #NOTE: we can't use `whence -a` because it's not supported in older versions of ksh
       whence -v "$cmd" 2>&1
     ) 2> /dev/null | grep -v 'not found' | grep 'builtin' > /dev/null 2>&1
  then
    #No-op
    :
  else
    printf "$cmd is not a built-in\n" >&2
    return 1
  fi
}

使用解决方案

在您选择的外壳中应用上述解决方案后,您可以像这样使用它......

在命令行:

$ isbuiltin command

如果命令是内置命令,则不打印任何内容;否则,它会向stderr打印一条消息。

或者您可以在脚本中使用它:

if isbuiltin $cmd 2> /dev/null
then
  echo "$cmd is a built-in"
else
  echo "$cmd is NOT a built-in"
fi