Commands And Arguments

BASH reads commands from its input (which is either a terminal or a file). These commands can be aliases, functions, builtins, keywords, or executables.

Each command can be followed by arguments. Arguments are words you specify after the command name. Arguments are separated from the command name and from each other by white space. This is important to remember. For example, the following is wrong:

    $ [-f file]

You want the [ command name to be separated from the arguments -f, file and ]. If you do not separate [ and -f from each other with whitespace, bash will think you are trying to execute the command name [-f and look in PATH for a program named [-f. Additionally, the arguments file and ] also need to be separated by spaces. The [ command expects the last argument to be ]. The correct command separates all arguments with spaces:

    $ [ -f file ]

NOTE:
It is very important that you understand how this works exactly. If you don't grasp these concepts well, the quality of your code will degrade significantly and you will introduce very dangerous bugs. Read Argument Splitting very carefully.

    $ ls
    a  b  c

ls is a command that lists files in the current directory. It's intended to be used only for producing human-readable results. Please don't try to parse, pipe, grep, capture, read, or loop over the output of ls in a script. It's dangerous and there's always a better way. While an invaluable tool on the interactive shell, ls should therefore never be used in scripts. You will understand why as you go through this guide.

    $ mkdir d
    $ cd d
    $ ls

mkdir is a command that creates a new directory. We specified the argument d to that command. This way, the application mkdir is instructed to create a directory called d. After that, we use the builtin command cd to change the shell's current directory to d. ls shows us that the current directory (which is now d) is empty, since it doesn't display any filenames.

In BASH scripts, arguments that were passed to the script are saved in 'Positional Parameters'. You can read these by using $1, $2, and so on for the respective argument. You can also use $@ and $* but more about this later on.


    $ type rm
    rm is hashed (/bin/rm)
    $ type cd
    cd is a shell builtin