Search anything:

Why is #! the first line in shell scripting ?

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Table of content

What is a Shell ?

  • A Unix shell is both a command interpreter and a programming language.
    • As a command interpreter, the shell provides the user interface to the rich set of GNU utilities.
    • As a programming language it allows these utilities to be combined.
  • Shells may be used interactively or non-interactively.
    • In interactive mode, they accept input typed from the keyboard.
    • In non-interactive mode, shells execute commands read from a file

Consider a shell program without the first line and study it's execution by the shell.

$ cat > lists
^D                                            Ctrl-D is end-of-file
$ chmod +x lists
$ ./lists

the ls command outputs the current directory content.

Sequence of Operation

  • The shell asks the kernel to run the script .

  • The program is not compiled rather than it is interpreted, so kernel returns a error not executable format file.

  • After receiving the error the shell understands that the program is a script.

  • Now the shell creates a child shell of /bin/sh to run the program.

The use of /bin/shas default shell to run program is fine when only one shell is preset but the current Unix systems contains more than one shell .

So to invoke any particular shell we use #!.

To see the list of shells available in system:-

$ cat /etc/shells
# Pathnames of valid login shells.
# See shells(5) for details.


When the first line starts with #! the kernel scans the rest of the line for full pathname of the interpreter to run the program.


$ cat > lists
#! /bin/fish
^D                                Ctrl-D is end of file
$ chmod +x lists
$ ./lists


Carefully choose the pathname to prevent cross vendor portability since different vendors puts different things in different places


/bin/fish vs /usr/bin/fish

Major types of Shells

  • Bourne Shell (sh) :- The Bourne shell was the default shell for Version 7 Unix and Unix-like systems.

  • C Shell (csh) :- The C shell was created to look more like the C programming language and that it should be better for interactive use. An improved version was tcsh.

  • Bash Shell (bash) :- bash is an acronym for ‘Bourne-Again SHell’. It incorporates useful features from the Korn shell ksh and the C shell csh.

  • Z Shell (zsh) :- Z Shell is an extended Bourne shell with many improvements, including some features of bash, ksh, and tcsh.

Why is #! the first line in shell scripting ?
Share this