tags:

views:

183

answers:

5

Hi, I have just started using Linux and I am curious how are shell built-in commands such as "cd" defined. Also, if someone could please explain how it is implemented and executed?

Thanks, Manjari

A: 

http://ss64.com/bash/ this will help you.

and here is shell scripting guide

http://www.freeos.com/guides/lsst/

moon
+6  A: 

If you want to see how bash builtins are defined then you just need to look at Section 4 of The Bash Man Page.

If, however, you want to know how bash bultins are implemented, you'll need to look at the Bash source code because these commands are compiled into the bash executable.

One fast and easy way to see whether or not a command is a bash builtin is to use the help command. Example, help cd will show you how the bash builtin of 'cd' is defined. Similarly for help echo.

SiegeX
+1  A: 

Manjari, Check the source code of bash shell from ftp://ftp.gnu.org/gnu/bash/bash-2.05b.tar.gz You will find that the definition of shell built-in commands in not in a separate binary executable but its within the shell binary itself (the name shell built-in clearly suggests this).

Hans Raj
+1  A: 

A Shell builtin -- http://linux.about.com/library/cmd/blcmdl1_builtin.htm for eg. -

which cd 
/usr/bin/which: no cd in (/usr/bin:/usr/local/bin......

Not a shell builtin but a binary.

which ls
/bin/ls
Spidermonkey
Not entirely true - sometimes builtins and executables overlap, eg. although there is '/bin/echo' program, most shells provide theirn own `echo` builtin.
el.pescado
+1  A: 

Actual set of built-ins varies from shell to shell. There are:

  • Special built-in utilities, which must be built-in, because they have some special properties
  • Regular built-in utilities, which are almost always built-in, because of the performance or other considerations
  • Any standard utility can be also built-in if the implementer of Shell wishes.

You can find out whether the utility is built-in using type command, which is supported by most shells (though its output is not standardized). Example from dash:

$ type ls
ls is /bin/ls
$ type cd
cd is a shell builtin
$ type exit
exit is a special shell builtin

Re cd utility, theoretically there's nothing preventing shell implementer to implement it as external command. cd cannot change the shell's current directory directly, but, for instance, cd could communicate new directory to the shell process via socket. But nobody does so because there's no point. Except very old shells (where there was not a notion of built-ins), where cd used some dirty system hack to do its job.

How cd is implementing inside the shell? Basic algorithm is described here. It can also do some work to support shell's extra features.

Roman Cheplyaka