# Topic 2: Finding Your Way on a Linux System (weight: 8)

## 2.1 Command Line Basics

 Weight 2 Description Basics of using the Linux command line.

Key Knowledge Areas:

• Basic shell
• Formatting commands
• Working With Options
• Variables
• Globbing
• Quoting

### Basic Shell

The Linux/Unix shell refers to a special program that allows you to interact with it by entering certain commands from the keyboard; the shell will execute the commands and display its output on the monitor. The environment of interaction is text-based and since it is command-oriented this type of interface is termed Command Line interface or CLI. Before the advent of GUI-based computing environments, the CLI was the only way that one can interact and access a computer system.

The shell is a very powerful place, and a lot is achieved through it. A lot of the front-end GUI methods of doing things have similar ways and means to get done with using the shell.

Shell accepts your instruction or commands in English (mostly) and if its a valid command, it is pass to kernel. It is a user program or it's environment provided for user interaction. Shell is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file.

Several shell available with Linux including:

Shell Name Developed by Where Remark
BASH ( Bourne-Again SHell ) Brian Fox and Chet Ramey Free Software Foundation Most common shell in Linux. It's Freeware shell.
CSH (C SHell) Bill Joy University of California (For BSD) The C shell's syntax and usage are very similar tothe C programming language.
KSH (Korn SHell) David Korn AT & T Bell Labs
--
TCSH See the man page.Type $man tcsh -- TCSH is an enhanced but completely compatible version of the Berkeley UNIX C shell (CSH). Tip: To find all available shells in your system type following command: $ cat /etc/shells


Note that each shell does the same job, but each understand a different command syntax and provides different built-in functions.

Any of the above shell reads command from user (via Keyboard or Mouse) and tells Linux Os what users want. If we are giving commands from keyboard it is called command line interface ( Usually in-front of $prompt, This prompt is depend upon your shell and Environment that you set or by your System Administrator, therefore you may get different prompt ). Tip: To find your current shell type following command $ echo $SHELL  #### Starting a shell Since it is most likely that you are in the graphical desktop environment now, the underlying shell that is available is not displayed. To access a shell, try the following key combination, Control + Alt + F1  Where F1 can be replaced by F2, F3, and so on. The graphical desktop tends to run in F7 or F8, so to go back to your graphical desktop screen, just hit Control + Alt + F7. These are virtual terminals. #### What shell am i running? echo$SHELL should work. But here is old good UNIX trick. Use the command ps with -p {pid} option, which selects the processes whose process ID numbers appear in pid. Use following command to find out what shell you are in:

ps -p $$ So what is  argument passed to -p option? Remember  returns the PID (process identification number) of the current process, and the current process is your shell. So running a ps on that number displays a process status listing of your shell. In that listing you will find the name of your shell (look for CMD column) .  ps -p$$


Output:

 PID TTY          TIME CMD
6453 pts/0    00:00:00 csh


From my Linux box:

$ps -p$$ Output:  PID TTY TIME CMD 5866 pts/0 00:00:00 bash  ### Formatting commands Notes 1. LINUX IS CASE-SENSITIVE. For example: Netscape, NETSCAPE and nEtscape are three different commands. Also my_filE, my_file, and my_FILE are three different files. Your user login name and password are also case sensitive. (This goes with the tradition of UNIX and the "c" programming language being case sensitive.) 2. Under Linux, all directories appear under a single directory tree 3. Files with names starting with "." are normally not shown by the ls (list) or dir commands. Think of these files as "hidden". Use ls -a (list with the option "all") to see these files. When you start a shell, display such as below (or similar) will be seen: root@lordb-PC:~#  or lordb@lordb-PC:-$


To enter a command, the following general syntax applies:- (Note: the $or # at the beginning of the command is simply the last part of the prompt and part of the command) $ COMMANDNAME [OPTIONS] [ARGUMENTS]


Example

$date  Output Thu Feb 16 16:57:32 CAT 2012  Some commands can execute without options or arguments like the date command above Arguments A command-line argument or parameter is an argument sent to a program being called. In principle a program can take many command-line arguments, the meaning and importance of which depend entirely upon the program. When a command processor is active a program is typically invoked by typing its name followed by command-line arguments (if any). For example, in Unix and Unix-like environments, an example of a command-line argument is: rm file.s  "file.s" is a command-line argument which tells the program rm to remove the file "file.s". Command-line option A command-line option or simply option (also known as a flag or switch) modifies the operation of a command; the effect is determined by the command's program. Options follow the command name on the command line, separated by spaces. A space before the first option is not always required. rm -f file.s  Option -f forces removal of file.s (ignore nonexistent files, never prompt) #### Basic commands ls - Short listing of directory contents ls [OPTION]... [FILE]...  OPTIONS -a list hidden files -d list the name of the current directory -l long listing giving details about files and directories -R list all subdirectories encountered -t sort by time modified instead of name  pwd Print working directory, i.e., display the name of my current directory on the screen. date Print or change the operating system date and time. E.g., I could change the date and time to 2000-12-31 23:57 using this command: date 123123572000 who Determine the users logged on the machine. ps ps axu | more  List all the processes currently running, even those without the controlling terminal, together with the name of the user that owns each process. su su - run a shell with substitute user and group IDs su [OPTION]... [-] [USER [ARG]...]  Example su lordb  Switch user to user lordb echo echo - display a line of text or value of variable echo$PATH


Show the content of the environment variable "PATH". This command can be used to show other environment variables as well. Use "set" to see the full environment.

#### Variables

Types of variables

Global variables

Global variables or environment variables are available in all shells. The env or printenv commands can be used to display environment variables. Below is a typical output: Shell variables are in uppercase characters by convention. Bash keeps a list of two types of variables:

lordb ~> printenv
CC=gcc
CDPATH=.:~:/usr/local:/usr:/
CFLAGS=-O2 -fomit-frame-pointer
COLORTERM=gnome-terminal
CXXFLAGS=-O2 -fomit-frame-pointer
DISPLAY=:0


Local variables

Local variables are only available in the current shell. Using the set built-in command without any options will display a list of all variables (including environment variables) and functions. The output will be sorted according to the current locale and displayed in a reusable format.

Creating variables

Variables are case sensitive and capitalized by default. Giving local variables a lowercase name is a convention which is sometimes applied. However, you are free to use the names you want or to mix cases. Variables can also contain digits, but a name starting with a digit is not allowed:

prompt> export 1number=1
bash: export: 1number=1': not a valid identifier


To set a variable in the shell, use

VARNAME="value"


Putting spaces around the equal sign will cause errors. It is a good habit to quote content strings when assigning values to variables: this will reduce the chance that you make errors.

Some examples using upper and lower cases, numbers and spaces:

lordb:~$MYVAR1="2" lordb:~$ echo $MYVAR1 2  Exporting variables A variable created like the ones in the example above is only available to the current shell. It is a local variable: child processes of the current shell will not be aware of this variable. In order to pass variables to a subshell, we need to export them using the export built-in command. Variables that are exported are referred to as environment variables. Setting and exporting is usually done in one step: export VARNAME="value"  A subshell can change variables it inherited from the parent, but the changes made by the child don't affect the parent. This is demonstrated in the example: lordb:~$ full_name="Franky M. Singh"
lordb:~$bash lordb:~$ echo $full_name lordb:~$ exit
lordb:~$export full_name lordb:~$ bash
lordb:~$echo$full_name
Franky M. Singh
lordb:~$export full_name="Charles the Great" lordb:~$ echo $full_name Charles the Great lordb:~$ exit
lordb:~$echo$full_name
Franky M. Singh
lordb:~$ When first trying to read the value of full_name in a subshell, it is not there (echo shows a null string). The subshell quits, and full_name is exported in the parent - a variable can be exported after it has been assigned a value. Then a new subshell is started, in which the variable exported from the parent is visible. The variable is changed to hold another name, but the value for this variable in the parent stays the same. Reserved variables Variable name Definition HOME The current user's home directory; the default for the cd built-in. The value of this variable is also used by tilde expansion. HOSTNAME The name of the current host. HISTSIZE The maximum number of commands to remember on the history list, default is 500. PATH A colon-separated list of directories in which the shell looks for commands. PS1 The primary prompt string. The default value is "'\s-\v\$ '".
PWD The current working directory as set by the cd built-in command.

#### Globbing

Bash does carry out filename expansion, a process known as "globbing". Globbing recognizes and expands wildcards. Globbing interprets the standard wildcard characters, * and ?, character lists in square brackets, and certain other special characters (such as ^ for negating the sense of a match). There are some important limitations on wildcard characters in globbing, however. Strings containing * will not match filenames that start with a dot, as, for example, .bashrc.

Example

bash$ls -l total 2 -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 a.1 -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 b.1 -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 c.1 -rw-rw-r-- 1 bozo bozo 466 Aug 6 17:48 t2.sh -rw-rw-r-- 1 bozo bozo 758 Jul 30 09:02 test1.txt bash$ ls -l t?.sh
-rw-rw-r--    1 bozo  bozo       466 Aug  6 17:48 t2.sh

bash$ls -l [ab]* -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 a.1 -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 b.1 bash$ ls -l [a-c]*
-rw-rw-r--    1 bozo  bozo         0 Aug  6 18:42 a.1
-rw-rw-r--    1 bozo  bozo         0 Aug  6 18:42 b.1
-rw-rw-r--    1 bozo  bozo         0 Aug  6 18:42 c.1

bash$ls -l [^ab]* -rw-rw-r-- 1 bozo bozo 0 Aug 6 18:42 c.1 -rw-rw-r-- 1 bozo bozo 466 Aug 6 17:48 t2.sh -rw-rw-r-- 1 bozo bozo 758 Jul 30 09:02 test1.txt bash$ ls -l {b*,c*,*est*}
-rw-rw-r--    1 bozo  bozo         0 Aug  6 18:42 b.1
-rw-rw-r--    1 bozo  bozo         0 Aug  6 18:42 c.1
-rw-rw-r--    1 bozo  bozo       758 Jul 30 09:02 test1.txt

bash$echo * a.1 b.1 c.1 t2.sh test1.txt bash$ echo t*
t2.sh test1.txt


#### Quoting

There are three types of quotes:

Quote type Name Meaning Example (type at shell prompt)
"
The double quote The double quote ( "quote" ) protects everything enclosed between two double quote marks except $, ', " and \.Use the double quotes when you want only variables and command substitution. * Variable - Yes * Wildcards - No * Command substitution - yes The double quotes allowes to print the value of$SHELL variable, disables the meaning of wildcards, and finally allows command substitution.
echo "$SHELL"echo "/etc/*.conf"echo "Today is$(date)"

'
The single quote The single quote ( 'quote' ) protects everything enclosed between two single quote marks. It is used to turn off the special meaning of all characters.
* Variable - No
* Wildcards - No
* Command substitution - No
The single quotes prevents displaying variable $SHELL value, disabled the meaning of wildcards /etc/*.conf, and finally command substitution ($date) itself.
echo '$SHELL'echo '/etc/*.conf'echo 'Today is$(date)'

\
The Backslash Use backslash to change the special meaning of the characters or to escape special characters within the text such as quotation marks. You can use \ before dollar sign to tell the shell to have no special meaning. Disable the meaning of the next character in $PATH (i.e. do not display value of$PATH variable):
echo "Path is \$PATH"echo "Path is$PATH"  
##### The Backslash

The backslash ( \ ) alters the special meaning of the ' and " i.e. it will escape or cancel the special meaning of the next character. The following will display filename in double quote:

FILE="/etc/resolv.conf"
echo "File is \"$FILE\" " Sample Outputs: File is "/etc/resolv.conf" The following will remove the special meaning of the dollar ($ ) sign:

FILE="/etc/resolv.conf"
echo "File is \$FILE " Sample Outputs: File is$FILE 
##### Protecting command line arguments

Type the following command to find out all c program file (*.c):

find $HOME -name *.c In the above example, the *.c is expanded by the bash shell. It will try to match all filename ending with .c in the /home directory (current user's home directory) such as main.c, lib1.c, lib2.c, ssh.c, auth.c etc. You can escape the wild card using the backslash as the escape character: find$HOME -name \*.c
find $HOME -name \*main.c find /nas01/apps/admin -iname \*py You can also use the double quote find$HOME -name "*.c"

#### Meaning of quotes

Normally, these characters are special to the shell: \ ' "  < > [ ] ? | ; # $^ & * ( ) = <Space> <Tab> <Newline> There are four different types of quotes: backslash (\), single quotes (apostrophes, '), double quotes (quotation marks, "), and backquotes (). 1. The backslash \ means: disable the special meaning of the subsequent character. 2. Quoting with '' (two apostrophes) means: quote exactly, disabling any special characters inside the quotes. 3. Quoting with "" means: disable the special characters inside the quotes except for$  \
4. The pair  (two backquotes) means: do a command substitution inside the backquotes first. So what is inside the backquotes is executed by the shell first, and then the output is passed to the command outside the quotes. The same can also be acomplished with $(command) which nests better than backquotes. ### Summary The following is a partial list of the used files, terms and utilities: • echo • history • PATH env variable • which Nice to know: • Substitutions • ||, && and ; control operators ## 2.2 Using the Command Line to Get Help  Weight 2 Description Running help commands and navigation of the various help systems. Key Knowledge Areas: • Man • Info The following is a partial list of the used files, terms and utilities: • man • info • Man pages • /usr/share/doc • locate Nice to know: • apropos, whatis, whereis ### How to Get Help Need help figuring out what a command is supposed to do? In an operating system with strange-sounding commands like awk, grep, and sed, it's not surprising. The man command (short for manual) is a source of online help for most Linux commands . For example, you can enter $ man grep


to learn all the secrets of the very useful grep command. (For a summary of the most-used Li nux commands, see the section "Important Linux Commands").

If man claims no knowledge of the command in which you're interested, try help instead.

$help  This command will list all the built-in bash commands with a brief syntax summary. Another help format called info is more powerful, since it provides hypertext links to make reading large documents much easier, but not all documentation is available in info format. T here are some very complete info documents on various aspects of Red Hat (especially the portions from the GNU project). To try it out, use the info command without any arguments. $ info


It will present you with a list o f available documentation. Press h to read the help for first-time users, or use the tab key to move the cursor to a topic link and then press enter to follow the link. Pressing p returns you t o the previous page, n moves you to the next page, and u goes up one level of documentation. To exit info, press q

### help

Built-In Help for built-in commands are available from the help command. For example

help logout


Provides help on the logout command. Help just prints a few lines of text to the console. You may need to be in a shell for this to work.

Note that even common commands like cp and mv are not built-in. In addition, most built-in commands have man and info pages (see below) - so it is generally more useful to look in man or info first.

If you have no idea about what command you should use, but you have a vague idea about some keywords that may be related to the topic you want (e.g., you want to print something), you can use the apropos command, like this:

 apropos print


that will display a lot of things related to print.

### man

Man pages are a flexible format of help page: they can be viewed in the console, and can be viewed as HTML in a web browser. For example, to view the man page for cp, type

man cp


If you don't know the name of the command, you can search by using -k

man -k "copy"


Man is split into sections

1. Executable programs or shell commands
2. System calls (functions provided by the kernel)
3. Library calls (functions within program libraries)
4. Special files (usually found in /dev)
5. File formats and conventions eg /etc/passwd
6. Games
7. Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)
8. System administration commands (usually only for root)
9. Kernel routines [Non standard]

If a page with the same name is in more than one section, the correct one can be accessed by specifying the section number:

man 1 cp


alternatively, specify -a to walk through all the sections

man -a cp


Man pages can also be viewed in web browsers. Some web browsers, such as Konqueror allow you to use man: like a protocol - for example, typing

man:cp


into the location bar shows the man page for cp. More generally, however, the man command can generate an HTML file, and then display it in a browser by using the -H command with the browser of your choice - in this example, firefox:

man cp -Hfirefox


How to search the man pages for a particular word or phrase

Sometimes you need help with a particular file or program and are unsure exactly which manual page to look up. Thankfully there is a argument that you can use with man that will allow you to search through all the man pages for a particular keyword or phrase. This argument is the -K argument. The syntax for this command is the following:

man -K keyword


So for example, lets say that you wanted to search for all manual pages that contained the word fstab, you would type:

man -K fstab


This would then return a list of manual pages that contain that word and give you the option to view it (Y), skip it (N), or quit the search (Q). To view one of the matches simply press the y button and that particular manual page will show.

### info

Info pages are another type of help page. Pages here are sometimes duplicates of man pages - and sometimes are more complete. To view an info page, type

info cp


### Yelp

Yelp is a graphical program to display help documentation on GNOME systems. Run the command 'yelp' to begin.

Summary

Type This . . . To Find This . . .
man -k [keyword] Search a database for commands that involve the keyword. Can also be used as apropos [keyword].
info [command] Display a file’s help information in an alternate format.
man [command] Display a file’s help information.
whatis [command] Display a short blurb about the command.

### The /usr/share/doc Directory Path

The Linux doc (for documentation) directory is the parent directory for a few hundred subdirectories that contain information regarding software components. All of the subdirectories begin with the name of a software package and may end in "-x.x.x", where the "x"s are numbers that show the current version number of the software.

For example, there may be a subdirectory below doc named bash-x.xx. The x.xx in the directory name, such as 2.05, shows the current version of the bash (Bourne Again Shell) installed on your system.

Linux Commands Training Tips: The Linux System Administration commands, concepts and tasks covered here apply to ALL other Linux distributions, including: Red Hat,  Ubuntu,  Kubuntu, Edubuntu, Slackware, Debian, SUSE, openSUSE - and Fedora.


Each of the subdirectories below doc, such as bash-x.xx contain help text files regarding the software components installed on your system.

A huge amount of useful information is included in these directories in files with names like: README, FAQ, INTRO and NEWS. If you are having difficulty with a software component, or even if you just want to know more about it, this is a good place to look for help and information.

Using ls and less to View the Linux Documentation Files in the doc Directory - Command Examples

$ls -l /usr/share/doc | less  Scroll down to see the Linux adduser, grep and info directories - and there are lots of other Linux documentation directories containing information used for system administration. Type in /user and press Enter to go to the first occurrence of "user" and then press "n" several times to go to the next occurrences. Press the letter q to quit out of the less command. ### The locate Command The locate command is often the simplest and quickest way to find the locations of files and directories on Linux and other Unix-like operating systems. The basic syntax for locate is: locate [options] name(s)  When used without any options, locate displays every absolute pathname for which the user has access permission that contains any of the names of files and/or directories that are provided to it as arguments (i.e., input data). The absolute pathname, also referred to as the absolute path or the full path, is the hierarchy of directories from the root directory to the designated file or directory. The root directory is the directory at the very top of the filesystem (i.e., hierarchy of files) that contains all other directories and files on the system and which is designated by a forward slash ( / ). It is important that the absolute pathname is returned both because it tells the exact locations on the system and because it makes it possible to indicate the locations of files or directories that have the same name but different absolute paths. Thus, for example, the following would list the absolute paths of all files named file1 and all directories named dir1 for which the user had access permission: locate file1 dir1  It would also list any other absolute pathnames that contained these strings (i.e., sequences of characters), for example /home/john/file123 or /usr/local/mydir1/index.html. The specificity of locate can be increased by using it together with wildcards or other regular expressions. Wildcards are characters that can be used to substitute for any other character or characters. For example, the star character ( * ) is a wildcard that can represent any single character or any string containing any number of characters. Regular expressions are a string that describes or matches a set of strings, according to certain syntax rules. For example, the following command uses the star wildcard to display all files on the system that have the .png filename extension: locate "*.png"  On some systems, such as Red Hat, the program slocate is installed by default instead of locate, and entering the locate command activates a script (i.e., a short program) that causes slocate to be launched. slocate provides a secure way to index and quickly search for files on a system by storing file permissions and ownership data so that users will not see files for which they do not have access. The -V option can be used to show which version of locate is used, including whether it is locate or slocate. Another way to determine whether slocate is being used is to see if an absolute pathname such as /usr/bin/slocate is returned when the following command is issued: locate locate  locate and slocate actually search a built-in database, named locate.db or slocate.db, respectively, rather than the entire hard disk drive itself, in order to provide a much shorter searching time. This database is automatically updated on a regular basis by cron, a small program that runs in the background, performing various tasks at regularly scheduled intervals. The updating is performed each night if the computer is on continuously. Because the database is not updated immediately, recently created files and directories might not show up when searching for them with locate or slocate. Fortunately, however, it is a simple matter to update the database manually, although it might take a few minutes. Manual updating can be accomplished by logging in as the root user (i.e., administrative user), such as by using the su (i.e., substitute user) command, and then issuing the following command: updatedb  The same thing can be accomplished by the root user by using locate with its -u (i.e., update) option, i.e., locate -u  For the curious, the database is located at /var/lib/slocate/slocate.db on some systems, such as Red Hat. Its exact location on any particular system can be found by the root user (because ordinary users will not have access permission on most systems) with the locate command as follows: locate locate.db  ### The Whatis Command Whatis is a funny command that's bound to come in handy, especially while you're learning Linux. By typing "whatis" followed by a command, Linux returns the first line of the Man-page (manual page) for that command. Here's an example to show you what the "cp" command does: $ whatis cp


This returns:

cp (1) - copy files and directories


The command is listed followed by a number in parentheses. The number refers to the section of the man-pages (manual pages) that the command can be found in. For the command ifconfig:

$whatis ifconfig  Returns ifconfig (8) - configure a network interface  If you wanted more information about one of the commands -- how it works and what the optional arguments are -- you would type: $ man ifconfig


And get back the explanation, all 176 lines worth.

NOTE: Some distros won't have a pre-built Whatis database. Instead of the descriptions above, you'll see a response telling you to build the database. In that case log on as root and type:

# /usr/sbin/makewhatis


### apropos

Because Linux knows so many commands, it's impossible to remember them all. (See, it's not just GUI-itis!) So here's a trick to help you. From a previous Linux Explorers tip you should know that if you type the first few characters of a command and press the Tab key, Linux will auto-complete the command or present you with a list of options for auto-completion:

We're going to be tricky and combine that feature with Whatis to really jog your memory, using the Apropos command.

Imagine you know only a part of the name or description of a command. Say for example, you remember "alsa," but not the whole of the command. Type:

$apropos alsa  This returns: aconnect (1) - ALSA sequencer connection manager alsaconf (8) - config tool for the Advanced Linux Sound Architecture alsactl (1) - advanced controls for ALSA soundcard driver alsamixer (1) - soundcard mixer for ALSA driver, with ncurses interface amidi (1) - read from and write to ALSA RawMIDI ports amixer (1) - command-line mixer for ALSA driver aplay (1) - command-line sound recorder and player for ALSA driver arecord [aplay] (1) - command-line recorder/player for ALSA driver aseqnet (1) - ALSA sequencer connectors over network  If you still weren't sure, you could use "$ man {command}" to get more information about each command.

Well, that is pretty cool isn't it? Very cool! But how cool is Linux, really? Way cool. Trust us.

$apropos cool  Output Smalledit-3.17.7 (1) - Stripped down version of Cooledit text editor cooledit (1) - Full featured X Window text editor for the System, v.11 coolicon (1) - Icon manager with graphical icon and drag and drop coolman (1) - X Window Man page reader based on the Coolwidget library sane-coolscan (5) - SANE backend for Nikon film-scanners  They don't come cooler than that, do they? ### The whereis Command The whereis command is used to locate the binary, the source code and the online manual page for any specified program. A binary is an executable (i.e., ready to run) form of a program. Source code is the original form of a program as written by a human using a programming language and before it has been converted by a compiler into a binary. The online manual pages, commonly referred to as man pages, are normally accessed using the man command. whereis's basic syntax is whereis [option(s)] program_name(s)  When used without any options, which is most commonly the case, whereis attempts to supply the absolute path names (i.e., the path to the root directory) for the binary, source code and man page for every program name (including command names, which are generally the same as program names) that is supplied to it as an argument (i.e., input). Any number of names can be accepted as arguments, and the results for each will be returned on a separate line. Thus, for example, the following would be used to attempt to find the locations of the executable, source code and man page for the ls command (which is used to list the contents of any specified directory): whereis ls  Although whereis ideally returns three pieces of information for each argument, in reality it often returns fewer and sometimes returns more. For example, it will not return a location for source code for a program on a computer for which the source code has not been installed (which is common when programs are installed in precompiled form during installation of the operating system). Likewise, there may be no man pages for some commands, or there may be more than one. ## 2.3 Using Directories and Listing Files  Weight 2 Description Navigation of home and system directories and listing files in various locations. Key Knowledge Areas: • Files, directories • Hidden files and directories • Home • Absolute and relative paths The following is a partial list of the used files, terms and utilities: • Common options for ls • Recursive listings • cd • . and .. • home and ~ Nice to know: ### List Files and Folders with Linux ls Command The Linux ls command is used to list files and folders in a directory. There are tons of options to use on the ls command. I will not cover every single option that you can use with the linux ls command. I will cover the most common options for the ls command. If you don’t find what you are looking for in this Linux tutorial then I would recommend running man ls and reading the man pages for the ls command. The usage for the Linux ls command is: ls [options] [file|directory]  You can use the ls command without any options or as many options as you like. Example lordb@lordb:~$ ls


Output

lordb@lordb:~$ls Android jujucharms nmaplog.nmap Templates archives lauchpadtxt.asc nmaplog.xml Ubuntu One Audiobooks lauchpadtxt.txt nohup.out vboxISOs Desktop lordb.pub packagelist.txt Videos Documents lsfile PacketTracer5 VirtualBox VMs Downloads lu Pictures vpd.properties errorlog ManageEngine Podcasts zd_backup examples.desktop Music Public zdesktop lordb@lordb:~$


If you just run ls with no options it will output the list of files in the current working directory in alphabetical order. So if you are in $HOME (which is the system variable for your home directory ( /home/username ). This will also not output any .* files or directories ( files or directories that start with . as they are hidden files|directories ). Now if you want to list all files and folders in a directory you can use ls -a or --all option. This option will output all files and folders including the files and folders that match .* ( your hidden files and folders ). You can also use ls -A or ls --almost-all which will output all files|directories except for ./ and ../ ( which ./ is current working directory, ../ is your parent directory ). Another common option for ls is using ls -b or ls --escape which will escape any special characters like spaces. This is more useful if you can not figure out which characters need escaped or if you are writing a script that needs the characters escaped. ls -l will output the files and directories in long list format. Which means ls -l will output your file and directory permissions, hardlinks or entries, user, group, size (in bytes), month, date, time, filename|directory name. ls -h will display the output sizes in human readable form, the highest available measurement. ( 1K 1M 1G.. etc ). This option has to be used with an option that outputs size as well. So either ls -s or ls -l but you would combine the options, ls -lh or ls -sh will work. You can combine a number of options for ls to get the results you want, ls -lha will display the output of all files and directories in long list format with the sizes being human readable aka the highest measurement available. You can also pass the output onto other commands using a pipe | so that you can alter the results more to specific needs. For example if you want to just see the sizes of files, and not filename or directory names: ls -sh | awk '{print$1}' will do this for you. If you wanted to display just the permissions of the files and directories, you could use ls -l | awk '{print \$1}' which will give you those results. If you want more information on scripting like this I will be covering this in another section.

I hope this beginner Linux tutorial on the Linux ls command has helped you accomplish what you need and also give you a better understanding on how the ls command works. Continue reading through the beginner Linux tutorial website for more Linux tutorials!

### The cd Command

The cd command is used to change the current directory (i.e., the directory in which the user is currently working) in Linux and other Unix-like operating systems. It is similar to the CD and CHDIR commands in MS-DOS. cd's syntax is

cd [option] [directory]


The items in square brackets are optional. When used without specifying any directory name, cd returns the user to the previous current directory. This provides a convenient means of toggling between two directories.

When a directory name is provided, cd changes the current directory to it. The name can be expressed as an absolute pathname (i.e., location relative to the root directory) or as a local pathname (i.e., location relative to the current directory). It is usually more convenient to use a local pathname when changing to a subdirectory of the current directory.

As an example, the following would change the current directory, regardless of where it is on the system (because it is an absolute path), to the root directory (which is represented by a forward slash):

cd /


Likewise, the following would change the current directory, regardless of its location, to the /usr/sbin directory (which contains non-vital system utilities that are used by the system administrator):

cd /usr/sbin


If a user currently in the directory /usr/local/share/man/ desired to change to the directory /usr/local/share/man/man2, which is a subdirectory of the current directory, it would be possible to change by using the absolute pathname, i.e.,

cd /usr/local/share/man/man2


However, it would clearly be much less tedious to use the relative pathname, i.e.,

cd man2


On Unix-like operating systems the current directory is represented by a single dot and its parent directory (i.e., the directory that contains it) is represented by two consecutive dots. Thus, it is possible (and often convenient) to change to the parent of the current directory by using the following:

cd ..


Another convenient feature of cd is the ability for any user to return directly to its home directory by merely using a tilde as the argument. A home directory, also called a login directory, is the directory on a Unix-like operating system that serves as the repository for a user's personal files, directories and programs. It is also the directory that a user is first in after logging into the system. A tilde is a short, wavy, horizontal line character that represents the home directory of the current user. That is, any user can return immediately to its home directory by typing the following and then pressing the Enter key:

cd ~


This is easier than typing the full name of the user's home directory, for instance, /home/josephine in the case of a user named josephine. (And it is just one of the numerous shortcuts that help make the command line on Unix-like operating systems so easy to use.)

When followed by a space and then a hyphen, cd both returns the user to the previous current directory and reports on a new line the absolute pathname of that directory. This can further enhance the already convenient toggling capability of cd. Toggling is particularly convenient when at least one of the two directories has a long absolute pathname, such as /usr/local/share/man/man2.

cd has only two options, and neither of them are commonly used. The -P option instructs cd to use the physical directory structure instead of following symbolic links. The -L option forces symbolic links to be followed.

### pwd

The pwd command reports the full path to the current directory.

The current directory is the directory in which a user is currently operating while using a command line interface. A command line interface is an all-text display mode and it is provided via a console (i.e., a display mode in which the entire screen is text only) or via a terminal window (i.e., a text-only window in a GUI).

The full path, also called an absolute path, to a directory or file is the complete hierarchy of directories from the root directory to and including that directory or file. The root directory, which is designated by a forward slash (/), is the base directory on the filesystem (i.e., hierarchy of directories), and it contains all other directories, subdirectories and files on the system. Thus, the full path for any directory or file always begins with a forward slash.

pwd is one of the most basic commands in Linux and other Unix-like operating systems, along with ls, which is used to list the contents of the current directory, and cd, which is used to change the current directory.

pwd's syntax is

   pwd [option]


Unlike most commands, pwd is almost always used just by itself, i.e.,

   pwd


## 2.4 Creating, Moving and Deleting Files

 Weight 2 Description Create, move and delete files and directories under the home directory.

Key Knowledge Areas:

• Files and directories
• Case sensitivity
• Simple globbing and quoting

The following is a partial list of the used files, terms and utilities:

• mv, cp, rm, touch
• mkdir, rmdir

Nice to know:

### The touch Command

The touch command is the easiest way to create new, empty files. It is also used to change the timestamps (i.e., dates and times of the most recent access and modification) on existing files and directories.

touch's syntax is

   touch [option] file_name(s)


When used without any options, touch creates new files for any file names that are provided as arguments (i.e., input data) if files with such names do not already exist. Touch can create any number of files simultaneously.

Thus, for example, the following command would create three new, empty files named file1, file2 and file3:

   touch file1 file2 file3


A nice feature of touch is that, in contrast to some commands such as cp (which is used to copy files and directories) and mv (which is used to move or rename files and directories), it does not automatically overwrite (i.e., erase the contents of) existing files with the same name. Rather, it merely changes the last access times for such files to the current time.

Several of touch's options are specifically designed to allow the user to change the timestamps for files. For example, the -a option changes only the access time, while the -m option changes only the modification time. The use of both of these options together changes both the access and modification times to the current time, for example:

   touch -am file3


The -r (i.e., reference) option followed directly by a space and then by a file name tells touch to use that file's time stamps instead of current time. For example, the following would tell it to use the times of file4 for file5:

   touch -r file4 file5


### The cp Command

The cp command is used to copy files and directories. The copies become independent of the originals (i.e., a subsequent change in one will not affect the other).

cp's basic syntax is

   cp [options] name new_name


As a safety precaution, by default cp only copies files and not directories. If a file with the same name as that assigned to the copy of a file (or a directory with the same name as that assigned to the copy of a directory) already exists, it will be overwritten (i.e., its contents will be lost). However, the owner, group and permissions for the copy become the same as those of the file with the same name that it replaced. The last access time of the source file and the last modification time of the new file are set to the time the copying was performed.

When a copy is made of a file or directory, the copy must have a different name than the original if it is to be placed in the same directory as the original. However, the copy can have the same name if it is made in a different directory. Thus, for example, a file in the current directory (i.e., the directory in which the user is currently working) named file1 could be copied with the same name into another directory, such as into /home/john/, as follows:

   cp file1 /home/john/file1


Any number of files can be simultaneously copied into another directory by listing their names followed by the name of the directory. cp is an intelligent command and knows to do this when only the final argument (i.e., piece of input data) is a directory. The files copied into the directory will all have the same names as the originals. Thus, for example, the following would copy the files named file2, file3 and file4 into a directory named dir1:

   cp file2 file3 file4 dir1


The -r (i.e., recursive) option, which can also be written with an upper case R, allows directories including all of their contents to be copied. (Directories are not copied by default in order to make it more difficult for users to accidentally overwrite existing directories which have the same name as that assigned to the copy being made and which might contain critical directory structures or important data.) Thus, for example, the following command would make a copy of an existing directory called dir2, inclusive of all it contents (i.e., files, subdirectories, their subdirectories, etc.), called dir3:

   cp -r dir2 dir3


The -i (i.e., interactive) option prompts the user in the event that any name assigned to a copy is already in use by another file and that file would thus be overwritten. Entering the letter y (either lower case or upper case) in response to the prompt causes the command to continue; any other answer prevents the command from overwriting the file. Thus, for example, if it is desired to make a copy of a directory called dir4 and call it dir5 and if a directory named dir4 already exists, the following would prompt the user prior to replacing any files with identical names in the latter directory:

   cp -ri dir4 dir5


The -a option preserves as much of the structure and attributes of the original directory and its contents as possible in the new directory and is thus useful for creating archives. It is similar to the -r option in that it copies directories recursively; however, it also never follows symbolic links. It is equivalent to the -rdp combination of options.

All the files in a directory can be copied to another directory by using the star wildcard. The star character represents any single character or any combination of characters. Thus, for example, the following would copy all of the files in a directory named dir6 into another existing directory called dir7:

   cp dir6/* dir7


cp can also be used with the star wildcard or other pattern matching characters to selectively copy files and directories. For example, to copy all of the files in the current directory that have the filename extension .html into another existing directory called dir8, the following would be used:

   cp *.html dir8


In this case, the star wildcard represents anything whose name ends with the .html extension.

Among the other options for cp are -b, which makes backup copies of each destination file, -f (i.e., force), which removes destination files that cannot be opened and tries again, -s, which makes symbolic links instead of copying, -u (i.e., update), which copies only if the source file is newer than the destination file or if the destination file is missing, -v (i.e., verbose), which makes brief comments about what is going on, and -x, which tells cp to stay on the same filesystem.

### The mkdir Command

The mkdir command is is used to create new directories.

A directory, referred to as a folder in some operating systems, appears to the user as a container for other directories and files. However, Unix-like operating systems treat directories as merely a special type of file that contains a list of file names and their corresponding inode numbers. Each inode number refers to an inode, which is located in inode tables (which are kept at strategic locations around the filesystem) and which contains all information about a file (e.g., size, permissions and date of creation) except its name and the actual data that the file contains.

mkdir has the following syntax:

   mkdir [option] directory_name(s)


directory_name is the name of any directory that the user is asking mkdir to create. Any number of directories can be created simultaneously.

Thus, for example, the following command would create three directories within the current directory (i.e., the directory in which the user is currently working) with the names dir_1, dir_2 and dir_3:

   mkdir dir_1 dir_2 dir_3


If a directory name provided as an argument (i.e., input) to mkdir is the same as that of an existing directory or file in the same directory in which the user is asking mkdir to create the new directory, mkdir will return a warning message such as mkdir: cannot create directory dir_1': File exists and will not create a file with that name. However, it will then continue to create directories for any other names provided as arguments.

It is necessary for a user to have write permission (i.e., permission from the system to create or change a file or directory) in the parent directory (i.e., the directory in which the new directory is to be created) in order to be able to create a new directory.

Directories created by mkdir automatically include two hidden directories, one representing the directory just created (and represented by a single dot) and the other representing its parent directory (and represented by two consecutive dots). This can be seen by using the ls (i.e., list) command with its -a option, which tells ls to show all directories and files, (including hidden ones) in any directory provided to it as an argument, or in the current directory if there are no arguments, i.e.,

   ls -a


### The mv Command

The mv command is used to rename and move files and directories. Its general syntax is:

   mv [options] argument(s)


The arguments are names of files and directories. If two file names are provided as arguments, mv renames the first as the second. If a list of arguments is provided and the final argument in the sequence is the name of an existing directory, mv moves all of the other items into that directory. If the final argument is not an existing directory and more than two arguments are provided, an error message is returned.

mv's syntax can also be expressed in a less general form as:

   mv [options] source target


If the target file is located in the same directory as the source file, then the source file can only be renamed. If both are in different directories, then the source file is moved to the directory named in the target argument, in which it can keep its original name or be assigned a new name. If the target is a directory, then the source file or directory is moved into that directory and retains its original name.

Thus, for example, the following would rename a file called file1 to file2, while keeping it in the current directory (i.e., the directory in which the user is currently working):

   mv file1 file2


The following would move a file named file3, without changing its name, from the current directory to an existing subdirectory of the current directory named dir1:

   mv file3 dir1/file3


mv can be used to move any number of files and directories simultaneously. For example, the following command moves all files and directories, including all the contents of those directories, from the current directory to the directory /home/alice/new/:

   mv * /home/alice/new/


The asterisk is a wildcard character that represents any string (i.e., sequence of characters). Thus, in the above example it represents the name of every file and directory in the current directory.

mv makes it as easy to move a file or directory up the hierarchy of directories (i.e., closer to the root directory) as down it. For example, the following would move a file named file4, which is currently located in the sub-subdirectory dir/dir/ of the user's home directory, to the top level in the user's home directory:

   mv dir/dir/file4 ~


The root directory is the directory that contains all other directories on a Unix-like operating system and which is at the top of the hierarchy of directories. A user's home directory is the directory in which a user finds itself by default after logging into the system and which can be represented by the tilde (wavy horizontal line character).

By default, mv does not provide any confirmation on the display screen if its action is completed without problems. This is consistent with the rule of silence tenet of the Unix philosophy.

Thus it is wise for users new to Unix-like operating systems to always use the -i option, which makes mv interactive in the situation in which files and/or directories with the same name already exist in the destination directory. For example, the above command would be made interactive as follows:

   mv -i * /home/alice/new/


Among mv's few other options are -b, which tells it to make a backup copy of each file that would otherwise be overwritten or removed, and -v, which tells it to be verbose and display the name of each file before moving it. Detailed information (including all options) about mv can be obtained by using its --help option, and information about the current version can be obtained by using its --version option.

### The rmdir Command

The rmdir command is used to remove empty directories in Linux and other Unix-like operating systems.

Often referred to as a folder in the Macintosh and Microsoft Windows operating systems, a directory in Linux is merely a special type of file that contains a list of file names and the corresponding inodes for each file and directory that it appears (to the user) to contain. An inode is a data structure (i.e., a way of storing data so that it can be used efficiently) that stores all the information about a file except its name and its actual data.

The syntax for rmdir is

   rmdir [option] directory_names


When used without any options, rm will delete any empty directories whose names are supplied as arguments (i.e., inputs) regardless of whether such directories have write permission or not. Thus, for example, the following command would remove two empty directories named dir1 and dir2 that are located in the current directory (i.e., the directory in which the user is currently working):

   rmdir dir1 dir2


The ability to remove only empty directories is a built-in safeguard that helps prevent the accidental loss of data. This is important because once deleted, it is extremely difficult or impossible to recover deleted data on Unix-like operating systems1.

The -p (i.e., parents) option tells rmdir to remove the parent directories of the specified directory if each successive parent directory will, in turn, become empty and if each parent directory has write permission. Thus, for example, the following would remove dir5, dir4 and dir3 if dir5 were empty, dir4 only contained dir5 and dir3 only contained dir4 (which, in turn, contained dir5):

   rmdir -p dir3/dir4/dir5


This provides a nice symmetry with the -p option of the mkdir command, which is used to create directories. Thus, the above set of nested directories could be easily created with the following:

   mkdir -p dir3/dir4/dir5


In contrast to the rm command, which is used to delete both files and directories, there is no -r option for rmdir. at least on the GNU version that is standard on Linux. That option allows rm to recursively delete a directory by first deleting all of its contents, beginning with those in the lowest levels of subdirectories. Thus, if a user wants to remove an entire directory structure, it is usually most efficient to use rm with its -r option rather than trying to first remove the contents of each directory, its subdirectories, etc.

### The rm Command

The rm (i.e., remove) command is used to delete files and directories on Linux and other Unix-like operating systems.

The general syntax for rm is:

   rm [options] [-r directories] filenames


The items in square brackets are optional. When used just with the names of one or more files, rm deletes all those files without requiring confirmation by the user. Thus, in the following example, rm would immediately delete the files named file1, file2 and file3, assuming that all three are located in the current directory (i.e., the directory in which the user is currently working):

   rm file1 file2 file3


Error messages are returned if a file does not exist or if the user does not have the appropriate permission to delete it. Write-protected files prompt the user for a confirmation (with a y for yes and an n for no) before removal. Files located in write-protected directories can never be removed, even if those files are not write-protected.

The -f (i.e., force) option tells rm to remove all specified files, whether write-protected or not, without prompting the user. It does not display an error message or return error status if a specified file does not exist. However, if an attempt is made to remove files in a write-protected directory, this option will not suppress an error message.

The -i (i.e., interactive) option tells rm to prompt the user for confirmation before removing each file and directory. If both the -f and -i options are specified, the last one specified takes affect.

As a safety measure, rm does not delete directories by default. In order to delete directories, it is necessary to use the -r option, which is the same as the -R option. This option recursively removes directories and their contents in the argument list; that is, the specified directories will first be emptied of any subdirectories (including their subdirectories and files, etc.) and files and then removed. The user is normally prompted for removal of any write-protected files in the directories unless the -f option is used.

If a file encountered by rm is a symbolic link, the link is removed, but the file or directory to which that link refers will not be affected. A user does not need write permission to delete a symbolic link, as long as the user has write permission for the directory in which that link resides.

The rm command supports the -- (two consecutive dashes) parameter as a delimiter that indicates the end of the options. This is useful when the name of a file or directory begins with a dash or hyphen. For example, the following removes a directory named -dir1:

   rm -r -- -dir1
`

Other options include -v (i.e., verbose), which provides additional information about what is happening, --help, which provides basic documentation about rm, and --version, which tells the version of rm that is currently in use. Some differences exist among the various versions of rm, so it is always wise to read the documentation for the particular system.

The rmdir command differs from rm in that it is only used to remove empty directories.