Home Previous Up Next3.2. Commandline does NOT scare!
About
Contents
Projects
Thwab
Articles
Downloads
عربي

3.2. Commandline does NOT scare!

Section quotes:

  • "Command, n.: Statement presented by a human and accepted by a computer in such a manner as to make the human feel as if he is in control."
        -- found on 'fortune-mod'
  • "Well then, UNIX is intuitive, because you only need to learn 5000 commands, and then everything else follows from that!"
        -- someone making fun of commands on 'comp.os.linux.misc'.

Section contents:

3.2.1. Introduction.

Command line in GNU/Linux systems is one of it's bet features, it allows you to do very complicated things with very simple command, it's natural to find a command line window always opened on desktops of expert Linux users, although Linux command line is an interpreter-based computer programming langauge, any non-expert user could use it simply.

You could use any program is your commands interpreter (you are free, this is what FSF all about) , we call them shells, GNU BASH is most widely use shell, it's the default shell on GNU/Linux systems, but you could use other shells like ksh,csh,tcsh,...etc.

 Tip

Bourne Again Shell (BASH) is so called because Bourne has made a nice shell which is called Bourne shell 'sh', later more featured shells appeared like korn shell 'ksh' and C-like shell 'csh' and 'tcsh' and Bourne shell was forgotten, one of its fans, has developed it to add all missing features and more, he call it Bourne Again Shell, it's part of GNU preject reflecting GNU philosophy that any scripting languages should be a real programming language, designed for writing and maintaining substantial programs.

Shell should not be confused with terminal, terminal is a device or program that emulate it (with graphical or text user interface), if you want to have a command line window you run a terminal emulator program (as usual there are many, and you are free), there are nice looking partially transparent terminal with internationalization support, drag and drop, on the other hand there are fast ugly black and white terminals, like:

  • 'xterm' - the most ugly terminal emulator for X, it seems very weird for non-UNIX users.
  • 'rxvt' - lesser ugly terminal emulator, colorful and usues less memory ('krxvt' and 'crxvt' supports Japanese and Chinese characters)
  • 'aterm' - a beautiful terminal emulator that supports partial transparent background, originated from Afterstep Window Manager.
  • 'eterm' - another one related to Enlightenment Window Manager.
  • 'wterm' - another one related to Window Maker.
  • 'mlterm' - multi-lingual terminal emuulator.
  • 'konsole' - nice terminal emulator for KDE desktop that supports partial transparent background.
  • 'gnome-terminal' - nice terminal emulator for GNOME desktop that supports partial transparent background.
usually terminal emulator icons looks like a black screen (with a shell), you may find it on 'Main menu -> System tools -> terminal'.

The text screen (non graphical) is called console, also called virtual terminal(VT) or pseudo-terminal, most distributions run seven virtual terminals (as if you have seven computers!),the last one is the graphical X server, press 'CTRL+ALT+Fn' (where Fn is F1,F2,...etc), for example to the first pseudo-terminal press 'CTRL+ALT+F1', then you use see a screen ask you for login name and password, enter them (you will not see what you are typing while entering your password), press CTRL+ALT+F2 and you will move to the second pseudo-terminal and so on. You could decrease number terminals to save resources or increase them to enjoy wasting of resources.

Once you have accessed to terminal (command line), you see a prompt like '[folder@host]$' for regular user and '[folder@host]#' for root, this is done to warn your that any typo mistake while you are root will distroy the system, if a regular user type commands that could case a damage he will get 'permission denied', the prompt style also could be changed.
Start typing commands (becareful that GNU/Linux is case sensitve 'A' need not be equal to 'a') , once you have forgotten the spelling or something type leading some letters then press TAB and BASH will complete it for use, if there are more than one possibility press another TAB (ie. two TABs), then read what you type and make sure it's what you mean then press ENTER:

# instead of typing
cd /home/ali/
# you could type
cd /h[TAB]a[TAB]
# but if there are 'ali' and 'ahmad' that starts with 'a' type
cd /h[TAB]a[TAB][TAB]
# which will become 'cd /home/a' and display:
ali	ahmad
# add 'l' to have 'cd /home/al' then press [TAB] and we are done
this feature is very useful with long file names like 'rocksndiamonds' game, just type first some letters then press [TAB], you could use up and down arrows to see commands history (it also keep them after reboot), for security users can acces their history not other users, use left and right arrows to move and correct what you type, also you could let BASH automatically correct your misspellings!!

3.2.2. Basic commands.

This tables lists basic commands, what is between brackets '[ ]' is optional, and pipe '|' means this or that, and '...' it could be many times, and to distingusih between what you should type literally and what you substitute with what you read, we use bold and italic respectively. It's not complicated as it may seem, so skip through the table and use it as fast reference while you are reading examples below:

cd [DIR] to enter DIR folder (directory), with no arguments it will goto your home directory, and 'cd -' will go back to the previous directory, 'cd ..' will go to the parent directory of the current directory, 'cd /' will goto the root directory.
pwd display present(current) working direcory.
ls [-lhFa] [PATTERN] display files (list) that match PATTERN, 'l' for detailed list, 'h' for human readable file sizes, 'F' will add suffix to distinguish file types, and 'a' will display all files including hidden files with leading '.' and more.
clear clear the screen.
echo ["STRING"]
printf "STRING1" ["STRING2"]...
the first will display STRING to standard output, the second uses C-like sytax the first is the format and the rest are arguments.
help [BUILTINCOMMMAND] display help about a BASH builtin command.
whatis [NAME]
man [NAME]
info [NAME]
display help about a command or a file, for example 'man ls', 'info grub' (in both press 'q' to quit) and 'whatis gedit', if 'whatis' in not available use 'mkwhatis'.
apropos [NAME] Search the 'whatis' database for a string, eg. 'apropos keyboard leds' (you may need to run 'mkwhatis' first).
less [FILE]
more [FILE]
display a file, page by page(that's why they are called pagers), use arrows, PageUP, PageDown and ENTER (press 'q' to quit)
cat [FILE]... display a file (or files) at once, in other words it's not interactive, (what it realy does is that concatenate file together and send them to it's standard output)
dd [if=FILE1] [of=FILE2] [bs=N] [count=M] sends M blocks each with size N bytes (unless suffixed with k for kilobytes or M for megabytes), from the first file ('if' means input file), to the second file ('of' means output file), if any not specified it will be assumed to be standard input/output, it is usually used with device files.
cp [-aRvi] SOURCE... DEST
mv [-aRvi] SOURCE... DEST
rm [-Rv] SOURCE... DEST
'cp', 'mv' and 'rm' are copy, move (copy and remove source, or rename) from source to destination (target) and delete (remove) file,options are :
'i' interactive, asks for 'are you sure?'
'v' be verbose, what it's doing.
'a' preserve attributes.
'R' recursive copy/move/remove sub-directory.
mkdir DIR...
rmdir DIR...
create a new directory, or remove empty directory, respectively.
ln [-sf] FILE_OR_DIR LINK
sln FILE_OR_DIR LINK
create a link (shortcut) that points to the first file/drectory (to have two copies of the file in two places without consuming disk space), options are:
's' to have soft/symblic link appear as a link with 'ls -l'
'f' force replacing the link if it pre-exists, the other program 'sln' do the same thing (create softt links) but it's a static file that depends on no library so that it could be used to manage library links even is basic library links are broken.
su [USER] to become another user, if not specified then it's assumed to be root (you will be asked for his password)
whoami it tells you who you are! it display your login name.
file [PATTERN] display filenames and their types in a human readable format (based on it's structure not on it's last period), like 'English text file', 'ASCII C text file', 'MPEG video file' ...etc.
df [-hbkmg] [PARTITION_MNT_PT | DIR]
du [-hbkmg] [FILE_OR_DIR]
display space available(free) or used by a directory measured by 'b' for bytes, 'k' for kilobytes, 'm' for megabytes, 'g' gigabytes and 'h' for human readable format.
free display free space of memory or swap virtual memory.
COMMAND1 ; COMMAND2 [ ; COMMAND3]... execute COMMAND1 then COMMAND2 and so on.
COMMAND1 && COMMAND2 [ && COMMAND3]... execute COMMAND1 and if it returns success then execute COMMAND2 and so on.
COMMAND1 || COMMAND2 [ || COMMAND3]... execute COMMAND1, if it fails then execute COMMAND2 and so on.
COMMAND1 & execute COMMAND1 on the background (you can execute more commands without waiting it to finish).
COMMAND1 | COMMAND2 sends first program standard output to the second program as it's standard input, we call this 'pipe'.
`COMMAND` this is not a command you type, it means to substitute COMMAND output in it's place, the (`) is NOT single quote, it's over '~', also could be used as '$(COMMAND)'.
$VARIABLE this is not a command, it means to substitute environment VARIABLE value.
VARIABLE=VALUE assign VALUE to environment VARIABLE (no spaces).
set display all environment variables and their values.
COMMAND [ < FILE1 ] [ > FILE2 ] use FILE1 as standard input and FILE2 as standard output.
COMMAND [ < FILE ] [ << "STRING" ] use FILE as standard input from the first line until the first "STRING" on a line by itself.
COMMAND [ >> FILE ] sends output of COMMAND to the end of FILE, its old contents won't be removed.
COMMAND [ 1> FILE1 ] [ 2> FILE2 ] sends standard input to FILE1 and standard error to FILE2.

to make recalling those command more easy know where it's name comes from:

cd (Change Dir ) , pwd (present working dir),ls(list) , man (manual page) , cp (copy) , mv (move) , rm (remove) , mkdir (Make Dir ) , rmdir (Remove Dir ) , ln (link) du (disk usage) , df (disk free) , su (super user)
also the options.
a (all ) , f (force) , R (recursive) , h (human readable) v (verbos :give info while working)

Few commands like 'pwd' and 'clear' works just by typing their names then pressing ENTER, while most commands accept some informations or options from the user to control their behavior this is called passing arguments (or parameters), they are typed after the command name (after a whitespace) before pressing ENTER.

 Tip

Most long options are typed using double hyphen '--', for example '--force --verbos', but for short options use a single hyphen '-' like '-f -v', and you could use one hyphen for both, to be '-fv', for example '-abcdef to mean '-a -b -c -d -e -f' and so on.

As you can see in that table you could get help about let's say 'bc' for example using 'man bc' which display 'bc' manual page (how to use), info bc displays more detailed GNU information pages (a complete reference), also information pages could have hyper-links(for branches) and it's classified into nodes. (move with arrows, press ENTER to follow a link, 'n' for next node, 'p' previous node and 'u' up node), in both manual and info pages you could use '/' and '?' to search and 'q' to quit.

Manual pages provide information about many topics (sections), they are in order:

  • 1. User commands.
  • 2. System calls (functions prvided by kernel).
  • 3. Subroutines (functions provided by programming libraries like 'libc')
  • 4. Devices (what each file in '/dev' for)
  • 5. File formats and protocols, for example the syntax of '/etc/lilo.conf'.
  • 6. Games.
  • 7. Miscellenous (Conventions and standards, macro packages, etc), for example the ASCII table.
  • 8. System Administation (root only) utilities.
  • 9. Linux kernel related.
  • n. New (unclassified) Documents.
  • l. Local manuals (manual you write for your own local use).

There could be more than one manual entry with the same name, for example there are 'printf' is a user command and a C library function, 'man printf' will show the command manual page not the function (see the order above), to show 'printf' function manual just specify the section number, like 'man 3 printf', an ugly looking program called 'xman' could be used to browse manual pages graphically, another way is to open your home directory then type 'man:printf' at the address, another way is to run 'khelpcenter' which is a part of KDE, then select UNIX manual pages from the sidebar then select a section like 5 (file formats) then choose a page like 'lilo.conf'

Manual from kde help center

To open GNU information pages with your file manager by typing something like 'info:xboard at the address, K help center could also open info pages, select 'Browse info pages' from the sidebar, then for example select 'games' then 'xboard'.

info from kde help center

3.2.3. Let's start typing commands.

Those are some examples of commands we have learnd, you could skip what start with '#' they are comments (the rest of the line is ignored), what you should type is in bold:

bash$ cd ~
bash$ pwd
/home/ali
bash$ whoami
ali
bash$ echo "Hello World"
Hello World
bash$ echo "any thing after hash" # is a comment,it has no effect
any thing after hash
bash$ echo "Hello `whoami`" # note ` not '(single quote)
Hello ali
bash$ su
password:********
bash# whoami
root
bash# exit
bash$ whoami
ali
bash$ ls -F
Projects/ readme.txt backround.jpeg test.sh*
bash$ ls -l
total 4
drwxr-xr-x 2	ali users	 4024 May 28 19:20 Projects
-rw-r--r-- 1	ali users	19106 May 28 19:20 readme.txt
-rw-r--r-- 1	ali users	 1224 May 28 19:20 backgrond.jpeg
-rwxr-xr-x 1	ali users	 1024 May 28 19:20 test.sh
bash$ echo "ali is the owner of the files
> and they belong to users group"
notice that ali is the owner of the files
and they belong to users group
bash$ gedit readme.txt # run 'gedit', you can't type more commands until gedit is closed
bash$ gedit readme.txt & # you could type more command because of &
bash$ mcedit readme.txt  # with no '&' because it's not a GUI program, press F10 to exit
... type something to fill two pages ... 
bash$ less readme.txt # press q to quit, / to search
bash$ ls -l /usr/lib | less # list file in pager
bash$ man file # press 'q', as in less
bash$ file * # see the result your self.
bash$ mc 
when we type, we will gett detialed file listting in which you can see fields in order: file mode (and permissions) the first letter in mode are once of 'd' for directory,'l' for link, 'c' for character device (one character at a time then it pass away) like keyboard, 'b' for block device (buffered, one block at a time) like hard disk, the rest letters are permissions for owner user, owner group and others, for each we have read 'r',write 'w' and execute 'x' flags, after modes we have a number that is 1 for regular files and for directories it's the number of subdirectories (plus two that are './' and '../'), then the owner user, group, file size time and file name.
 Tip

If the output of a command is more than one page you could use 'SHIFT+PGUP/SHIFT+PGDN' to see pages you miss,
you could copy and paste just highlight the text (drag the mouse over the text), then click the middle mouse button (both buttons if there is no middle button) or right click with some terminals.

To stop (exit) a program (like 'man') press 'CTRL+C' (in some documents it's written as 'Cc' or '^c'),
to send EOF signal, end of file you are typing, press 'CTRL+D',
although you could SHIFT+PageUp or SHIFT+PageDown to scroll the window of long output (like ls), you could pipe (with '|') the output to a pager like 'less' or 'more', command line users loves 'mc' (short for midnight commander) file manager (it looks like Norton commander for DOS but with more features) and 'mcedit' is part of that package.

If you want to type very long muliple line commands set, type '\' when you get too much on the right and press ENTER, a prompt to continue typing on next line, type '\' to have another line and so on, it will execute them when it face a line does not end with '\'.

bash$  echo "GNU/
> Linux"
GNU/
Linux
bash$  echo "GNU/\
> Linux"
GNU/Linux
bash$  ls /usr/bin/ \ 
>  /usr/sbin/ \ 
>  /usr/doc/ | \ 
>  less 
# this is equivalent to
bash$  ls /usr/bin/ /usr/sbin/ /usr/doc/ | less 

here is another session:

# notice this misspelling
[/@host]$ cd /hpme/ali # instead of 'cd /home/ali'
cd: /hpme/ali not found 
# for automatic correction of misspellings in cd command
[/@host]$ shopt -s cdspell 
[/@host]$ cd /hpme/ali # the same mistake.
/home/ali
[/home/ali@host]$  cd /user/ben 
/usr/bin
[/usr/bin@host]$ 
to enable spell correction type 'shopt -s cdspell', the bad news this should be done every time! how to execute this command automatically ? know that '/etc/profile' and your '~/.bashrc' will be executed each time you start BASH, add this command to the end of '/etc/profile' to enable it for all users or add to end of '~/.bashrc ' (recall '~' represents your own home directtory) to enable it just for you, you can add this line automatically with those commands:
# to add the command that enable spell checking for filenames
# only for you (~/.bashrc).
[~/@host]$  echo "shopt -s cdspell" >> ~/.bashrc 
# to do that for all users (you need to be root):
[~/@host]$ su root 
password:******
[/home/ahmad@host]# echo "shopt -s cdspell" >> /etc/profile 
[/home/ahmad@host]# exit 
[~/@host]$

Notice how we edited a file with one command line instead of opening a text editor and wait until it loads it's GUI then open the file then goto last line..., all what we did is to use 'echo' to display the line on standard output, but we change standard output from screen to the end of some file using double direction operation '>>'! (be careful if you use single direction operation '>', old file content will be removed)

 Tip

What is the commands needed to generate a file listing '/usr/bin' contents.

In this example we create a file without using text editor:

[~/@host]$  cat > test2.txt << HANGA 
Start Typing
You can have more that one line
To End the Typing, Type the Magic Word
HANGA
[~/@host]$  less test2.txt 
# 'cat' will send it's standard input(keyboard) to it's standard output
# that we set to be 'text2.txt', and we specify a "magic" word as the end
# of typing (or CTRL+D).

The behavior of some programs are affected by environment variables, the value of an environment variable is specified using '=' for example type 'my_age=25' then type 'echo $my_age', the dollar sign '$' is used to tell BASH to substitute 'my_age' with its value, type 'bash' to start a new BASH process then type 'echo $my_age' again to notice that the value is not preserved, we use 'export' shell builtin command followed by the environment variable to preserve its value over newly created child processes (ie. export it to them), type 'exit' and try 'export my_age=25'.

Environment variables could be used for many things, for example LANGUAGE is used to set the local language of a program. BASH uses many of environment variables they could be used to customize its behavior, for example, CDPATH environment variable is used as a semicolon separated list of directories in which to try incomplete 'cd' commands, notice the following session:

bash$ export CDPATH=.:/mnt:/usr/local:/usr/share/doc
bash$ cd win_c/temp
/mnt/win_c/temp
bash$ cd floppy
/mnt/floppy
bash$

Commands are executable files found on many directories (the current directory could be one of them), if there are two programs with the same name on different directories, you could know which one is called type 'which COMMAND', if you want to execute the other one, type it's full name. The set of directories to search for executables is called PATH, it's an environment variable.

# display 'cat' program location
[~/@host]$  which cat 
/bin/cat
# display 'PATH'
[~/@host]$  echo "$PATH" 
/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin:.
# to add a directory to PATH, on the least priority side:
[~/@host]$  PATH="$PATH:/MY_DIR" 
[~/@host]$  echo "$PATH" 
/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin:.:/MY_DIR
# to add a directory to PATH, on the most priority side:
[~/@host]$  PATH="/MY_FOLDER:$PATH" 
[~/@host]$  echo "$PATH" 
/MY_FOLDER:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin:.:/MY_DIR
# this change is temporary, it will be back to the original at next reboot
# notice that the current directory '.' usually be the last one. 
###############
# substitution could be done any where like
[~/@host]$  echo $EDITOR 
vim
[~/@host]$  $EDITOR 
# this will execute 'vim'

We have talked about commands that take a PATTERN as an argument like 'ls', not just a single file name, most commands do so (this is because BASH is doing this substitution) but few don't expect that (eg. 'mv *.jpg *.png' won't work as DOS users expect), it's useful because you give it a general pattern of files you like instead of mention them all, BASH will substitute matches. The pattern it self is a string with special wildcards those are:
* any thing with any length (including nothing) *term*any thing has 'term' (no matter where)
? any single character. S??autofsstarts with 'S' followed by two characters then 'autofs'
[SET] any member of the set [a-zA-z][0-9]a letter followed by a number
[^SET] any non member of the set [^0-9]a non digit character
{PAT1 [ ,PAT2]...} first pattern or second pattern,...etc *.{jpeg,png}any thing ends with '.jpeg' or '.png'
Wildcards (* and ?) are not supstituted with the leading dot (that is used to hide files), one may think of a solution like '.*' to represent hidden files, so that 'ls .* *' to list hidden and unhidden files, but be aware this is not correct, open the terminal and try it yourself (pipe it to less to see the output page by page), as you may notice the parent directory '..' was included! this is very dangerous, imagine the result of tryin to remove hidden files from the home of the root user '/root' by typing 'rm -r /root/.*', it will remove every thing on your system! The right way to represent hidden files is '.[^.]*' a dot followed by a non-dot then any thing.

So we have characters that has special non literal meaning, for example 'Why?' mean a 'Why' folloed by any single character, what to do if I mean a file called 'Why?' ? so how to repesent the literal character as is ? this is done using espace special character '\' just add it before ant special character, for example 'Why\?' means the wanted file, another example if you want to enter a directory called 'Mohammad Ali' you can't type 'cd Mohammad Ali' because 'cd' needs one argument and those are two, you should type 'cd Mohammad\ Ali' to escape SPACE from argument speparator to be normal space, another way is to use quotes, there are two types of quotes strong quote (single quote ') which represent it's content as is (and as single argument), the second type is week quote (double quote ") which do some substitution and escape special characters, for example it will work like 'cd "Mohammad Ali"' but if the folder name is '$Ali' it won't work as expected, it will substitute Ali environment variable value, to enter it use strong quote ("cd '$Ali'") or escape it.

 Warning

Do NOT name your files like those strange names having one or more of '$?#%\' characters, this could confuse you and breake some shell scripts. Do not confuse single quote (') with back quote (`) used to substitute output.

BASH could do integer arithmatics on constants or environment variables through let builtin and '$(( ))' both without using dollar sign '$' prefix of variable name, notice the following session

bash$ echo $((2+3*4))
14
bash$ let a=3; let b=2*a; echo "a=$a,b=$b"
a=3,b=6
# for C fans
bash$ let ++a; let b*=5; let c='(a<b)?a:b'
bash$ echo "a=$a,b=$b,c=$c"
a=4,b=30,c=4
bash$ help let | less
quotes in "let c='(a<b)?a:b'" are used so that the less than operation are not interpreted as redirection of input. In bare POSIX Bourne shell (sh) you need to use external tool like 'expr', try
bash$ expr 2 + 3 \* 4
14
bash$ expr substr "I love GNU/Linux." 12 5
Linux

ToC
Copyrights & Copylefts
What is Linux?
How to install Linux?
Halloween Documents

ArabEyes
Wikipedia
OpenSource
GNU
FSF's FSD
OSI's OSD
Linux.org
Linux.com
LinuxToday
SlashDot
FreshMeat
LWN.net

About Islam
What is Islam ?
We love Jesus; honored and not crucified.
Do you love Jesus or Paul ?
Who is Muhammad [PBUH] ?
Articles
Your scanner works on Linux
Linux cleaning Windows Viruses
Report
Unwanted Advertisements
Bugs and misspellings
Dead links:

 

Best viewed with free web browsers

You may get more high quality software from here for free
proud to be 100% Microsoft FREE GNU FDL


Generously Hosted by www.JadMadi.net

Previous Up 3.2. Commandline does NOT scare! Next
Copyright © 2007, Muayyad Saleh AlSadi