Using the Bash CLI

Basic Bash

Command line editing is covered elsewhere.

$ exit

Exit the shell. If the shell you are in has a parent shell then you will end up in it. If the shell you are in is the login shell then you can’t use the exit command. You’ll have to use logout.

Ctrl+D (which is the key sequence for EOF) is another way to exit the shell.

$ export EDITOR=vi VISUAL=vi

Sets the variables EDITOR and VISUAL.

It may be better to have these values set to the complete path for vi on your system.

export — specifies that those two variables are to propagate to subprocesses — thus becoming environment variables. In other words they are valid for this shell, a sub-shell, or a script you may run from the them. Child processes cannot export variables back to the parent processes which spawned them.

Although the built-in environment variables propagate to subprocesses, the shell must be explicitly told to do so with other variables, options, aliases, etc. The export command takes care of this — a more permanent way is to place their exported assignments in a bash configuration file (see below.)


$ source commandlist

executes comandlist/(a Bash script)


$ alias search=grep
$ alias cd_www='cd ~/sites/testing/www'
$ alias la='ls -al'
$ alias printdir='pr * | lpr'

When using an alias in a command line bash makes a textual substitution of the alias for that which it is aliasing.

Aliases can be used only for the beginning of a command string. You can’t simply alias a directory path then cd to it. However, bash has a way around this problem. If the value of an alias ends in a blank, then bash tries to do alias substitution on the next word on the command line.

Aliases are recursive — it is possible to alias an alias. However, bash has protection so that something like alias ls='ls -al' will not create an infinite loop. If the word to be replaced is the same as the alias name (of the current alias) then no text substitution takes place.

If you type alias name , the shell will print the alias’s value. If you type alias without any arguments, you get a list of all the aliases you have defined. The command unalias name removes any alias definition for its argument.

Aliases are good; but shell scripts and functions are better. You’ll need to know the order of precedence when an alias and a function have the same name.

Setting Bash Options

Options let you change the shell’s behavior. The basic commands are set -o optionname and set +o optionname. The - turns the named option on, while the + turns it off.

Option Description
emacs Enter emacs editing mode (on by default.)
ignoreeof Don’t allow use of a single CTRL-D to log off; use the exit command to log off immediately. This has the same effect as setting the shell variable IGNOREEOF=10.
noclobber  Don’t allow output redirection (>) to overwrite an existing file.
noglob Don’t expand filename wildcards like * and ?
nounset Indicate an error when trying to use a variable that is undefined.
vi Enter vi editing mode.

There are more options; And some options can be set just using a dash and letter following the set keyword.

set -o — List all options with their settings.

shopt is a newer built-in for configuring the shell. It is meant as a replacement for option configuration originally done through environment variables and the set command.

shopt options option-names is the format for this command. You can find tables which list both the options and the option-names.

cdable_vars — is a notable option-name. If set, an argument to the cd built-in command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.


Bash has some already built-in variables. Others you will define on your own.

varname=value — is how you declare/assign a variable.

If the value is more than one word, it must be surrounded by quotes. To use the value of a variable in a command, precede its name by a dollar sign ($).

$ echo "The value of \$varname  is \"$varname\"."

This works pretty much like it does in PHP. Single quotes (instead of double quotes) result in less interpretation. Also, you can omit the quotes entirely — although this is not advisable — because white space will be consolidated as everything is seen as a word separated by white space.

You should put double quotes around what you want to echo out — even if what you’re outputting is a single variable — the reason for this is to preserve the white space in the value of the variable.

$ LsOutput=`ls -al`
# Store command output in a variable using backquotes.
# For more on this see topic: Command Substitution

# Assign the value of one variable to another.

You can do this:

$ AB=/usr/dog/contagious/ringbearer/grind ; export AB
$ cd $AB

Two reasons why braces are used when dereferencing variables:

Reason 1

If you want to have other text right up against the output from an environment variable, surround the variable in braces. This protects the variable name from being misunderstood. For example:

$ echo ${AB}/adventure

Reason 2

Because that’s the normal way to dereference a variable. $varname is the exception — and $varname doesn’t work in many situations. Here’s a list of those situations:

  • if your code refers to more than nine positional parameters: you must use ${10} for the tenth instead of $10.
  • the variable name is followed by a character that is a letter
  • the variable name is followed by a character that ist a digit
  • the variable name is followed by a character that is an underscore

unset — If you decide that you no longer want a variable to be set, you can use the unset command to erase its value. For example, you could type unset XYZ, which would cause XYZ to have no value set.


PS1 determines your main prompt. PS2 determines your secondary prompt — and so on… If the shell needs additional input, it uses the value of PS2.

PS2 is called the secondary prompt string; its default value is >. It is used when you type an incomplete line and hit RETURN, as an indication that you must finish your command.

On my Mac this is what I have:

PS1 '\h:\W \u\$ '
PS2 '> '

Some prompt component escape sequences:

Command Meaning
\d The date in "Weekday Month Day" format
\e The ASCII escape character (033)
\H The hostname
\h The hostname up to the first "."
\n A carriage return and line feed
\s The name of the shell
\T The current time in 12-hour HH:MM:SS format
\t The current time in HH:MM:SS format
\@ The current time in 12-hour am/pm format
\u The username of the current user
\w The current working directory
\W The basename of the current working directory
\# The command number of the current command
\! The history number of the current command
\$ If the effective UID is 0 print a #, otherwise print a $
\nnn Character code in octal


BTW: I use the word “enter” to mean submit something to the shell.

This section is about:

Where does Bash look when you enter a command?

A command is a word you enter which correlates to the name of either (an executable file) or (a shell built-in construct.)

sameh-labibs-imac:~ samehlabib$ echo $PATH

This show the default path for a user (since it has not been customized for samehlabib.) Directories in the path list are separated by colons.

If you put an (executable file)/command in one of these directories, you can use the command just by entering it.

The order of path directories matters. Directories are checked going left to right.

type is a useful command in this regard.

sameh-labibs-imac:~ samehlabib$ type vi
vi is /usr/bin/vi

If a command lives in multiple PATH directories, you can use type with the -a option to list all the directories where the command lives.

Also, the type command shows just the command’s name and its type if it’s a built-in command (like echo), an alias, or a function.

If you often use directories of commands that are not in your PATH, you can permanently add them. To do this, add a new PATH variable to your .bashrc file. For example, to add a new directory called /dirname/bin to your path, add the following line:

$ PATH=$PATH:/dirname/bin ; export PATH

This first reads the current path directories into the new PATH then adds the /dirname/bin directory.


CDPATH does for directories what PATH does for commands. It makes using the cd command easier.

$ CDPATH=:~/fr/lang/clause/long

The colon in the beginning allows a directory to be found in the current directory.

Bash provides something else to help cd to a directy; if you set the shell option cdable_vars , any argument you supply to the cd command that is not a directory will be looked at as a potential variable. Hence you can store long directory paths in variables to avoid re-typing them.

This allows us to omit the dollar sign in front of the variable when applying cd to it.

(other) Environment Variables

Variable Its Value
HOME Path to your home directory
SECONDS Number of seconds since the shell was invoked
BASH Path of currently running shell command
BASH_VERSION The version number of the shell
BASH_VERSINFO An array of version information for the shell
PWD Current directory
OLDPWD Previous directory

Configuration Files

~/.bash_profile Here you will put lines which specify the values for intrinsic environment variables you want to change and commands which run or produce output when you log in. Also, here you’ll source your .bashrc if you want it’s content to apply to the login shell.
~/.bashrc Is referred to as the environment file. Use it to specify definitions for things in your environment (Not for intrinsic environment variables though but for variables you want to become environment variables, option and aliases.) This file is automatically read when a subshell is started. However, to have this file apply its content to the login shell you’ll need the line source .bashrc at the end of .bash_profile
/etc/profile .. is the global .bash_profile
/etc/bashrc .. is the global .bashrc
~/.bash_logout .. is read and executed every time a login shell exits.

.bash_profile, is read by bash every time you log in.

.bash_profile is read only by the login shell. If you start up a subshell, it will attempt to read commands from the file .bashrc. You can use the source command from within .bash_profile to execute .bashrc.

Some variables you can assign in .bash_profile:

PATH Make sure to include the existing path in your assignment to PATH.
SHELL SHELL=/bin/bash
EDITOR EDITOR=/usr/bin/vi
PS1 PS1='\h:\W \u\$ '
PS2 PS2='> '


fc for history

You don’t need fc if you use the history features of the vi command line editing.

fc is a built-in shell command.

The -l option to fc lists previous commands. Arguments:

  • two arguments, they serve as the first and last commands to be shown.
  • one number argument, only the command with that number is shown.
  • a single string argument, it searches for the most recent command starting with that string; then it shows everything from that command to the most recent command.
  • no arguments, you’ll see the last 16 commands entered. bash also has a built-in command called history ; which does the same thing.

-n suppresses the line numbers.

-s allows you to rerun a command. See man page to understand the arguments you can use with the -s option. Among other things this allows for string replacements.

When used without options fc loads the default editor. fc runs the command(s) after you edit them.

  • With no arguments, fc loads the editor with the most recent command.
  • With a numeric argument, fc loads the editor with the command with that number.
  • With a string argument, fc loads the most recent command starting with that string.
  • With two arguments to fc, the arguments specify the beginning and end of a range of commands, as above.

Although this may look like a good way to generate a shell script, a better way would be to direct the output of fc -ln to a file — then edit that file and execute the commands when you’re happy with them.

I skipped History Expansion. This Bash history stuff is too involved!

History Environment Variables

Variable Meaning
HISTCMD The history number of the current command
HISTCONTROL If set to the value of ignorespace, lines beginning with a space are not entered into the history list. If set to ignoredups, lines matching the last history line are not entered. Setting it to ignoreboth enables both options.
HISTIGNORE A list of patterns, separated by colons (:), used to decide which command lines to save in the history list. Patterns are considered to start at the beginning of the command line and must fully specify the line, i.e., no wildcard (*) is implicitly appended. The patterns are checked against the line after HISTCONTROL is applied. An ampersand (&) matches the previous line. An explicit & may be generated by escaping it with a backslash.
HISTFILE Name of history file in which the command history is saved. The default is ~/.bash_history.
HISTFILESIZE  The maximum number of lines to store in the history file. The default is 500. When this variable is assigned a value, the history file is truncated, if necessary, to the given number of lines.
HISTSIZE The maximum number of commands to remember in the command history. The default is 500.
FCEDIT Pathname of the editor to use with the fc command.


$ touch apple banana grape grapefruit watermelon

Is an example of how to create some empty files.

$ find /usr -print > /tmp/allusrfiles &

This command finds all files on your system (starting from the /usr directory), prints those file names, and puts those names in the file /tmp/allusrfiles. The ampersand (&) runs that command line in the background.

$ vi $(find / -print | grep xyzzy)

This vi command opens all filenames for editing (one at a time) that include xyzzy. This particular example may be useful if you knew that you wanted to edit a file for which you knew the name but not the location. As long as the string was fairly uncommon, you could find and open every instance of a particular filename existing in the file system.

$ echo "I am $[2002 - 1957] years old."
I am 45 years old.

In this example, the shell interprets the arithmetic expression first (2002 – 1957), and then passes that information to the echo command. The echo command displays the text, with the results of the arithmetic (45) inserted.

cd /home ; du -s * | sort -rn

This script looks at all directories in /home and reports on their size in kilobytes. The output is sorted numerically, with the largest directory at the top of the list.

$ cat /etc/password | sort | more

This command prints the contents of the /etc/password file and pipes the output to the sort command. The sort command takes the user names that begin each line of the /etc/password file, sorts them alphabetically, and pipes the output to the more command.

$ echo 'PS1="\W \!?> " ' >> ~/.bash_profile

Adds the line 'PS1="\W \!?> " ' to your ~/.bash_profile.

Make sure that you use two right-carets (>>). A single one will overwrite the file instead of appending to it.

$ ls -l $BASH_ENV
-rw-r—r-- 1 anthony  busdriver  124  Aug 10 01:50 /Users/anthony/.bashrc

In this example, you wanted to see the location of your bash environment file, and then check its size and when it was last changed.

$ export PATH=$PATH:/home/xyz/bin

In this example, I temporarily added the /home/xyz/bin directory to the PATH. This is useful if, during a shell session, you find yourself wanting to run a bunch of commands from a directory that is not normally in your PATH. This temporary addition saves you from typing the full or relative path each time you want to run a command.

$ jobs
[1]  Stopped (tty output)  vi /tmp/myfile
[2]  Running        find /usr -print > /tmp/allusrfiles &
[3]  Running        nroff -man /usr/man2/* >/tmp/man2 &
[4]- Running        nroff -man /usr/man3/* >/tmp/man3 &
[5]+ Stopped        nroff -man /usr/man4/* >/tmp/man4

To check which commands you have running in the background, use the jobs command. To see the process ID for the background job, add an -l option to the jobs command. If you type ps, you can use the process ID to figure out which command is associated with a particular background command.

Continuing with the example shown, you can bring any of the commands on the jobs list into the foreground. For example, if you are ready to edit myfile again, you can type:

$ fg %1

As a result, the vi command opens again, with all the text as it was when you stopped the vi job.

$ ps ax | less
$ kill [pid]

replace [pid] with a number

Use a virtual terminal. After you log in, you can look for the X process (ps ax | less)
and kill it (kill pid, where pid is the X process).

$ xlsfonts | wc -l

Xlsfonts outputs the names of all the fonts installed on your computer and wc -l counts how many were outputed.

$ ls -ld test
drwxr-xr-x  2 chris  sales   1024  Jan 24 12:17 test

# (excerpt from man ls)
# -d  If an argument is a directory, list only its name (not its
#     contents); often used with -l to get the status of a directory.

$ mount -t vfat /dev/fd0 /mnt/floppy
$ dd if=/dev/hda2 of=/mnt/floppy/bootsect.lnx bs=512 count=1
$ umount /mnt/floppy

Mounts a FAT formatted floppy, copies the first sector off the second partition, then unmounts the floppy.

Who am I?

  • user name
  • group name
  • user ID
  • group ID

To find out information about your identity, use the id command as follows:

$ id
uid=109(sameh) gid=102(devs) groups=102(devs),9(bigpeople),3(teachers)

These tell you sameh’s permissions.

You can see information about your current login session by using the who command. In the following example, the

  • -i option tells the who command to print the login time
  • -m says to print information about the current user
  • -H asks that a header be printed
$ who -imH
                    USER  LINE    LOGIN-TIME     IDLE  FROM!sameh  tty1    Jun 18 20:57     .

FROM can display the name of the remote computer which sameh logged in from — if it was a different system. IDLE time shows the user is currently working in the shell since a dot is displayed.


Every time you open a shell (interactive or non-interactive) or enter a command you are starting a subprocess.

Some shell things are known to subprocesses. By shell things I am referring to shell variables (built-in or otherwise), aliases, and options.

The phrase “environment variable” refers to a special class of shell things that are available to the login shell and all subprocesses. Some (Not all) built in shell variables are environment variables. There are three ways things can be environment variables:

  • They just are environment variables.
  • They are exported with the export command.
  • They are placed in the .bashrc file (a.k.a. environment file)

An environment variable does not have to be a variable. It could be an option or an alias.

Although environment variables are guaranteed to be known to subprocesses not all shell things are known to subprocesses.

The built-in variables HOME, MAIL, PATH, and PWD are environment variables.

For automatic exporting: set -a or set -o allexport.

$ export vars

Variable names separated by blanks. Can combine assignment and exportation:

$ export var1=val1 var2=val2 var3=val3

You can define variables to be for a particular subprocess (command) only, like this:

$ name=val command

This variable assignment won’t propagate beyond this command line. This “command” includes options and arguments.

$ export
# or
$ export -p

Displays all your environment variables and their values.

$ declare

Also, displays your environment variables. Actually, declare show you more stuff than export.

Here are some variables which are not built-in — but are commonly made into environment variables:

COLUMNS The number of columns of your display
EDITOR File path of your preferred editor
LINES number of lines in your display
SHELL File path for the shell which commands will use — if they need to spawn a subshell. Compare this with BASH.
TERM Your terminal’s type

Positional Parameters

This and some other content on this page is copied or derived from Advanced Bash-Scripting Guide by Mendel Cooper. This document may only be distributed subject to the terms and conditions set forth in the Open Publication License (version 1.0 or later), See the book to learn of all legal issues related to this intellectual property.

The most important special, built-in variables are called positional parameters. These hold the command-line arguments to scripts when they are invoked. Positional parameters have the names 1, 2, 3, etc., meaning that their values are denoted by $1, $2, $3, etc. There is also a positional parameter 0, whose value is the name of the script (i.e., the command typed in to invoke it).

Two special variables contain all of the positional parameters (except positional parameter 0): * and @. The difference between them is subtle but important, and it’s apparent only when they are within double quotes.

"$*" is a single string that consists of all of the positional parameters, separated by the first character in the environment variable IFS (internal field separator), which is a space, TAB, and NEWLINE by default. On the other hand, "$@" is equal to "$1" "$2"... "$N", where N is the number of positional parameters. That is, it’s equal to N separate double-quoted strings, which are separated by spaces. If there are no positional parameters, "$@" expands to nothing. We’ll explore the ramifications of this difference in a little while.

The variable # holds the number of positional parameters (as a character string). All of these variables are “read-only,” meaning that you can’t assign new values to them within scripts.

For example, assume that you have the following simple shell script:

echo "alice: $@"
echo "$0: $1 $2 $3 $4"
echo "$# arguments"

Assume further that the script is called alice. Then if you type alice in wonderland, you will see the following output:

alice: in wonderland
alice: in wonderland
2 arguments

In this case, $3 and $4 are unset, which means that the shell will substitute the empty (or null) string for them. [3]

[3] Unless the option nounset is turned on, in which case the shell will return an error message.

Shell functions use positional parameters and special variables like * and # in exactly the same way as shell scripts do. If you wanted to define alice as a function, you could put the following in your .bash_profile or environment file:

function alice
    echo "alice: $*"
    echo "$0: $1 $2 $3 $4"
    echo "$# arguments"

You will get the same result if you type alice in wonderland.

Typically, several shell functions are defined within a single shell script. Therefore each function will need to handle its own arguments, which in turn means that each function needs to keep track of positional parameters separately. Sure enough, each function has its own copies of these variables (even though functions don’t run in their own subshells, as scripts do); we say that such variables are local to the function.

However, other variables defined within functions are not local (they are global), meaning that their values are known throughout the entire shell script. For example, assume that you have a shell script called ascript that contains this:

function afunc
  echo in function: $0 $1 $2
  var1="in function"
  echo var1: $var1

var1="outside function"
echo var1: $var1
echo $0: $1 $2
afunc funcarg1 funcarg2
echo var1: $var1
echo $0: $1 $2

If you invoke this script by typing ascript arg1 arg2, you will see this output:

var1: outside function
ascript: arg1 arg2
in function: ascript funcarg1 funcarg2
var1: in function
var1: in function
ascript: arg1 arg2

In other words, the function afunc changes the value of the variable var1 from “outside function” to “in function,” and that change is known outside the function, while $1 and $2 have different values in the function and the main script. Notice that $0 doesn’t change because the function executes in the environment of the shell script and $0 takes the name of the script. Figure 4.2 shows the scope of each variable graphically.

Figure 4.2. Functions have their own positional parameters

Local Variables in Functions

A local statement inside a function definition makes the variables involved all become local to that function. The ability to define variables that are local to “subprogram” units (procedures, functions, subroutines, etc.) is necessary for writing large programs, because it helps keep subprograms independent of the main program and of each other.

Here is the function from our last example with the variable var1 made local:

function afunc
  local var1
  echo in function: $0 $1 $2

  var1="in function"
  echo var1: $var1

var1="outside function"
echo var1: $var1
echo $0: $1 $2
afunc funcarg1 funcarg2
echo var1: $var1
echo $0: $1 $2

Now the result of running ascript arg1 arg2 is:

var1: outside function
ascript: arg1 arg2
in function: ascript funcarg1 funcarg2
var1: in function
var1: outside function
ascript: arg1 arg2

Note that afunc now has its own, local copy of var1, although the original var1 would still be used by any other functions that ascript invokes.

Notice that (although $1 and $2 are independent of their script counterparts) $0 refers to the same thing in and out of the function. $0 always refers to the script name.

By default $1 and $2 are local when inside a function. Whereas, $0 is neither local or global — it’s just the name of the nearest script from above.

Quoting with $@ and $*

Now that we have this background, let’s take a closer look at "$@" and "$*". These variables are two of the shell’s greatest idiosyncracies, so we’ll discuss some of the most common sources of confusion.

  • Why are the elements of "$*" separated by the first character of IFS instead of just spaces? To give you output flexibility. As a simple example, let’s say you want to print a list of positional parameters separated by commas. This script would do it:

    echo "$*"

    Changing IFS in a script is risky, but it’s probably OK as long as nothing else in the script depends on it. If this script were called arglist, then the command arglist alice dormouse hatter would produce the output alice,dormouse,hatter. Chapter 5 and Chapter 10 contain other examples of changing IFS.

  • Why does "$@" act like N separate double-quoted strings? To allow you to use them again as separate values. For example, say you want to call a function within your script with the same list of positional parameters, like this:

    function countargs
        echo "$# args."

    Assume your script is called with the same arguments as arglist above. Then if it contains the command countargs "$*", the function will print 1 args. But if the command is countargs "$@", the function will print 3 args.

    File System

    $ ls -al CodeIgniter
    total 136
    drwxr-xr-x  17 samehlabib  staff    578 Nov 28 18:40 .
    drwxr-xr-x+ 44 samehlabib  staff   1496 Nov 26 19:10 ..
    drwxr-xr-x  11 samehlabib  staff    374 Nov 28 19:49 .git
    -rw-r--r--   1 samehlabib  staff    304 Nov 24 11:12 .gitignore
    -rw-r--r--   1 samehlabib  staff    771 Nov 28 18:40 .travis.yml
    -rw-r--r--   1 samehlabib  staff   1089 Nov 24 11:12 DCO.txt
    drwxr-xr-x  16 samehlabib  staff    544 Nov 24 11:12 application
    -rw-r--r--   1 samehlabib  staff    110 Nov 24 11:12 composer.json
    -rw-r--r--   1 samehlabib  staff   6611 Nov 24 11:12

    The plus (+) indicates a directory has subdirectories.

    Dot (.) by itself refers to the current directory.

    Dot dot (..) by itself refers to the parent directory.

    Dot before a file or directory name means it’s considered to be hidden.

    d in front of rwxr-xr-x means the listing is for a directory.

    A number (like 44 above) is the number of files.

    A number (like 578 above) is the number of bytes associated with the file (in the case of a directory it’s the number of bytes that make up the directory definition file.)

    samehlabib is the owner and he belongs to the staff group.

    The date and time refers to when a file was last modified.

    Bash’s cd in the form cd -, changes to previous directory. cd without an argument takes you to your home directory — just like cd ~.

    Create a Symlink

    $ sudo ln -s "/Apps/Sublime Text" /bin/subl
    # ln -s <destination> <linkname>
    # If linkname is w/o path then symlink is created in current directory
    # sudo command -- need root privilege to create things in /bin/subl
    # Quotes were used to hold together first argument because spaces.
    # There's also symlink command.

    Tilde (~) home-directory


    A file path which uses a tilde is considered an absolute-file-path.

    pwd (the command)

    Print the name of the current working directory.


    Create a directory.


    Change the permission on a file or directory.

    Commands (various aspects of using them)

    Options can have arguments.

    lp -d lp1 -h file

    The process of matching expressions containing wildcards to filenames is called wildcard expansion or globbing.

    Tilde expansion is another form of command line processing.

    Brace expansion (see next heading) can also be used for filepath expansion.

    Commands only see results of wildcard expansion — They see an argument list.

    wildcard what it matches
    ? any single character
    * any string — including an empty one
    [set] any one character in this set
    [!set] any one character not in this set

    You can specify a set using a dash-separated range of letters or numbers.

    the set what it matches
    [abc] a, b, or c
    [.,;] a period, comma, or semicolon
    [-_] a dash or an underscore
    [!0-9] any non-digit character
    [0-9!] any digits or an exclamation point
    [a-zA-Z] any lowercase or uppercase letter
    [a-zA-Z0-9_-] any letter, digit, underscore, or dash

    To match ! using set notation, place it after at least one other character, or precede it with a backslash — [\!].

    If no filenames are found which match then the shell will return the pattern itself.

    You can use wildcards as part of a pathname.

    ls /www*/[ikr]?

    Brace Expansion

    Whereas with filepath wildcard expansion the expression will expand to files and directories which exist, brace expansion expands to an arbitrary string.

    $ echo cam{co,per,d}s
    camcos campers camds

    It is also possible to nest braces, like vd{m{w,q,po},lpy}dv. This would give the same result as vd{mw,mq,mpo,lpy}dv.

    You can combine both types of expansion:

    ls *.{htm,html,php}
    # is equivalent to:  ls *.htm *.html *.php
    # I'm assuming ls can take multiple arguments.
    # If not, then it behaves as if ls can take multiple arguments

    Command Substitution

    One thing you can use command substitution for is to assign a value to a variable. It allows you to assign the standard output of a command to a named variable.

    Using backquotes (`) is one way to do this. However that’s not the best syntax for doing this. See example:

    $ LsOutput=`ls -al`
    # Store command output in a variable using backquotes.
    # The other way to do this is:
    $ LsOutput=$(ls -al)

    (for the line which has the $(command)) the command inside the parentheses is run, and anything the command writes to standard output is returned. These constructs can be nested.

    Besides using command substitution to assign a value to a variable name, you can use it to provide arguments to another command:

    vi $(grep -l 'needle' filename*)

    This opens up (into vi) every file (in the current directory whose name starts with filename) which contains needle.

    The -l option to grep causes it only to print names of files that contain matches.

    Command substitution (just like variable and tilde expansion) occurs inside double quotes.

    Arithmetic Expressions Expansion

    There are two forms you can use to expand an arithmetic expression and pass it to the shell: $[expression] or $((expression)). Here is an example:

    $ echo "There were $[2 + 6] monkeys at the zoo."
    There were 8 monkeys at the zoo.


    UNIX file I/O takes the form of arbitrarily long sequence of characters (bytes)—as opposed to blocks, records, or card images. Everything on the system that produces or accepts data is treated as a file; this includes hardware devices like disk drives and terminals.

    Standard I/O

    Every UNIX program that you run has these standard I/O streams:

    • standard input — defaults to keyboard
    • standard output — defaults to terminal display
    • standard error — defaults to terminal display

    Standard I/O streams can be redirected by the shell to a file or another program.

    Even a PHP script made for the command line will have these streams built in by default.

    Generally programs/commands take input from a file whose name is an argument; However, if you omit this filepath argument, the program will expect its input from the keyboard. Here is what you can expect if you omit the filepath:

    • If the program doesn’t expect input then it may just produce some output then return the shell prompt. Otherwise ..
    • You will be at the start of a new line (which may or may not have some type of prompt specific to this program.)
    • You are free to type on this line
    • You can enter a newline character (Enter key) to mark the end of a line and start to start typing on the next line.
    • Some character or string you type will mark the end of file (usually the ASCII character for EOF which is produced by the Ctrl-d a.k.a. ^D key) and cause the program to process your input. Some programs consider the newline character to be the mark of the end of file — hence the enter key will serve this goal — thus preventing you from entering a multiple line file (as your input.)
    • Program produces program output and error output.
    • Program may expect input again.
    • If the program took more input then it may produce more program output and error output.
    • Your shell prompt comes back when the program decides this is its appropriate response at that point in time.



    Redirect all output of a command into the standard input of another command.

    ps -ax | tee somefile.ascii | more
    cat /tmp/otherfile | sort | more


    < Direct the contents of a file to the command — assuming the command expects input from the keyboard.
    > Direct the output of a command to a file, deleting the existing file — assuming the command was going to output to the screen.
    >> Direct the output of a command to a file, adding the output to the end of the existing file — assuming the command was going to output to the screen.


    $ echo "My next colonoscopy is on $(nextappointment)" >> ~/appointments

    Redirection can be combined:

    command < filename1 > filename2

    The One Line Script using (;) Semicolon

    $ cd ; pwd ; ls

    Use a semicolon (;) to run commands in sequence.

    Utilities (UNIX Programs & Bash Built-ins)


    For information on individual bash built-in commands see the Bash Man Page or use the --help option with the command.

    The following is a comma separated list of built-ins: bash, :, ., [, alias, bg, bind, break, builtin, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, unalias, unset, wait

    Not Built-in

    Command What it’s for
    id To find out information about your identity.
    nslookup query Internet name servers interactively
    ifconfig Displays the status of the currently active network interfaces. Also, it serves as a command-line utility for configuring network interfaces.
    netstat show network status
    who Display who is logged in.
    route Manually manipulate the routing tables.
    uname Print operating system name.
    hostname Set or print name of current host system.
    domainname Set or print name of current YP/NIS domain.
    dmesg Display the system message buffer.
    mknod Make device special file.
    passwd modify a user’s password
    xset user preference utility for X
    startx initialize an X session
    less Types the contents of a file onto the screen one page at a time.
    tr The tr utility copies the standard input to the standard output with substitution or deletion of selected characters.
    file determine file type
    cat concatenate and print files
    head display first lines of a file
    tail output the last part of files
    sort sort lines of text files
    grep grep, egrep, fgrep – print lines matching a pattern
    cmp compare two files byte by byte
    diff compare files line by line
    sed stream editor
    awk pattern-directed scanning and processing language
    pr The pr utility is a printing and pagination filter for text files.
    cut cut out selected portions of each line of a file
    script make typescript of terminal session
    magic The file command’s magic pattern file.
    cd change working directory
    ls list directory contents
    basename basename, dirname — return filename or directory portion of pathname
    stat readlink, stat — display file status
    chmod change file modes or Access Control List
    touch change file access and modification times
    df display free disk space
    du estimate file space usage
    ln make links between files
    mount mount file systems
    mkdir make directories
    rmdir remove directories
    rm remove directory entries
    mv move files
    cp copy files
    find walk a file hierarchy
    pwd return working directory name
    locate find filenames quickly
    echo write arguments to the standard output
    tee The tee utility copies standard input to standard output, making a copy in zero or more files. The output is unbuffered.
    scp secure copy (remote file copy program)
    fdisk DOS partition maintenance program
    umount unmount filesystems
    shutdown close down the system at a given time
    resize set TERMCAP and terminal settings to current xterm window size
    dd convert and copy a file
    top display and update sorted information about processe
    ps process status
    nice execute a utility with an altered scheduling priority
    killall killall
    fuser list process IDs of all processes that have one or more files open
    at at, batch, atq, atrm — queue, examine, or delete jobs for later execution
    cron daemon to execute scheduled commands
    gzip compress or expand files
    tar manipulate tape archives
    date display or set date and time
    ntpdate set the date and time via NTP
    cal displays a calendar and the date of easter
    xargs construct argument list(s) and execute utility
    which locate a program file in the user’s path
    man format and display the on-line manual pages
    apropos search the whatis database for strings
    screen screen manager with VT100/ANSI terminal emulation
    clear clear the terminal screen
    tput initialize a terminal or query terminfo database
    terminfo terminal capability data base
    lpr print files
    lp print files
    pr print files
    sleep suspend execution for an interval of time
    su substitute user identity
    sudo execute a command as another user
    chpass add or change user database information
    talk talk to another user
    finger user information lookup program


About samehramzylabib

See About on
This entry was posted in UNIX Command Line. Bookmark the permalink.

One Response to Using the Bash CLI

  1. Pingback: Bash Vi Command Line Editing | Sam's PHP


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s