63
AddUsersHowto Command-line To add a user you must use the sudo command (for an explanation of what that means, see the RootSudo page). Here are the commands: To add a user. NOTE: do not use the useradd command. $ sudo adduser <username> To see the options for adding a user try the man command. $ man adduser Here is a useful example of the useradd command. Why use useradd? It gives a few more options for special cases. To add a user, give her a standard home directory in the /home folder and specify the shell she accesses by default do this: $ sudo useradd username -m -s /bin/bash $ sudo passwd username Groups You might also wish to create a new group for your users. # sudo addgroup <groupname> To add a new user to a existing group you would do this: # sudo adduser <username> audio To add an existing user to an existing group you can use the same command: # sudo adduser <username> <groupname> or # sudo usermod -aG <groupname> <username>

Learning the Shell

  • Upload
    -

  • View
    8

  • Download
    2

Embed Size (px)

DESCRIPTION

v

Citation preview

AddUsersHowtoCommand-lineTo add a user you must use thesudocommand (for an explanation of what that means, see theRootSudopage). Here are the commands:To add a user.NOTE:do not use the useradd command.$ sudo adduser To see the options for adding a user try themancommand.$ man adduserHere is a useful example of the useradd command. Why use useradd? It gives a few more options for special cases. To add a user, give her a standard home directory in the /home folder and specify the shell she accesses by default do this:$ sudo useradd username -m -s /bin/bash $ sudo passwd username GroupsYou might also wish to create a new group for your users.# sudo addgroup To add a new user to a existing group you would do this:# sudo adduser audioTo add an existing user to an existing group you can use the same command:# sudo adduser or# sudo usermod -aG

FilePermissionsUnderstanding and Using File PermissionsIn Linux and Unix, everything is a file. Directories are files, files are files and devices are files. Devices are usually referred to as a node; however, they are still files. All of the files on a system have permissions that allow or prevent others from viewing, modifying or executing. If the file is of type Directory then it restricts different actions than files and device nodes. The super user "root" has the ability to access any file on the system. Each file has access restrictions with permissions, user restrictions with owner/group association. Permissions are referred to as bits.To change or edit files that are owned by root,sudomust be usedIf the owner read & execute bit are on, then the permissions are:-r-x------There are three types of access restrictions:PermissionActionchmod option

read(view)r or 4

write(edit)w or 2

execute(execute)x or 1

There are also three types of user restrictions:Userlsoutput

owner-rwx------

group----rwx---

other-------rwx

Note:The restriction type scope is not inheritable: the file owner will be unaffected by restrictions set for his group or everybody else.Folder/Directory PermissionsDirectories have directory permissions. The directory permissions restrict different actions than with files or device nodes.PermissionActionchmod option

read(view contents, i.e. ls command)r or 4

write(create or remove files from dir)w or 2

execute(cd into directory)x or 1

1. read restricts or allows viewing the directories contents, i.e.lscommand2. write restricts or allows creating new files or deleting files in the directory. (Caution:write access for a directory allows deleting of files in the directory even if the user does not have write permissions for the file!)3. execute restricts or allows changing into the directory, i.e.cdcommandFolders (directories) must have 'execute' permissions set (x or 1), or folders (directories) will NOT FUNCTION as folders (directories) and WILL DISAPPEAR from view in the file browser (Nautilus).Permissions in Actionuser@host:/home/user$ ls -l /etc/hosts-rw-r--r-- 1 root root 288 2005-11-13 19:24 /etc/hostsuser@host:/home/user$Using the example above we have the file "/etc/hosts" which is owned by the user root and belongs to the root group.What are the permissions from the above /etc/hosts ls output?-rw-r--r--

owner = Read & Write (rw-)group = Read (r--)other = Read (r--)Changing PermissionsThe command to use when modifying permissions is chmod. There are two ways to modify permissions, with numbers or with letters. Using letters is easier to understand for most people. When modifying permissions be careful not to create security problems. Some files are configured to have very restrictive permissions to prevent unauthorized access. For example, the /etc/shadow file (file that stores all local user passwords) does not have permissions for regular users to read or otherwise access.user@host:/home/user# ls -l /etc/shadow-rw-r----- 1 root shadow 869 2005-11-08 13:16 /etc/shadowuser@host:/home/user#

Permissions:owner = Read & Write (rw-)group = Read (r--)other = None (---)

Ownership:owner = rootgroup = shadowchmod with LettersUsage: chmod {options} filenameOptionsDefinition

uowner

ggroup

oother

aall (same as ugo)

xexecute

wwrite

rread

+add permission

-remove permission

=set permission

Here are a few examples of chmod usage with letters (try these out on your system).First create some empty files:user@host:/home/user$ touch file1 file2 file3 file4user@host:/home/user$ ls -ltotal 0-rw-r--r-- 1 user user 0 Nov 19 20:13 file1-rw-r--r-- 1 user user 0 Nov 19 20:13 file2-rw-r--r-- 1 user user 0 Nov 19 20:13 file3-rw-r--r-- 1 user user 0 Nov 19 20:13 file4Add owner execute bit:user@host:/home/user$ chmod u+x file1user@host:/home/user$ ls -l file1-rwxr--r-- 1 user user 0 Nov 19 20:13 file1Add other write & execute bit:user@host:/home/user$ chmod o+wx file2user@host:/home/user$ ls -l file2-rw-r--rwx 1 user user 0 Nov 19 20:13 file2Remove group read bit:user@host:/home/user$ chmod g-r file3user@host:/home/user$ ls -l file3-rw----r-- 1 user user 0 Nov 19 20:13 file3Add read, write and execute to everyone:user@host:/home/user$ chmod ugo+rwx file4user@host:/home/user$ ls -l file4-rwxrwxrwx 1 user user 0 Nov 19 20:13 file4user@host:/home/user$chmod with NumbersUsage: chmod {options} filenameOptionsDefinition

#--owner

-#-group

--#other

1execute

2write

4read

Owner, Group and Other is represented by three numbers. To get the value for the options determine the type of access needed for the file then add.For example if you want a file that has -rw-rw-rwx permissions you will use the following:OwnerGroupOther

read & writeread & writeread, write & execute

4+2=64+2=64+2+1=7

user@host:/home/user$ chmod 667 filenameAnother example if you want a file that has --w-r-x--x permissions you will use the following:OwnerGroupOther

writeread & executeexecute

24+1=51

user@host:/home/user$ chmod 251 filenameHere are a few examples of chmod usage with numbers (try these out on your system).First create some empty files:user@host:/home/user$ touch file1 file2 file3 file4user@host:/home/user$ ls -ltotal 0-rw-r--r-- 1 user user 0 Nov 19 20:13 file1-rw-r--r-- 1 user user 0 Nov 19 20:13 file2-rw-r--r-- 1 user user 0 Nov 19 20:13 file3-rw-r--r-- 1 user user 0 Nov 19 20:13 file4Add owner execute bit:user@host:/home/user$ chmod 744 file1user@host:/home/user$ ls -l file1-rwxr--r-- 1 user user 0 Nov 19 20:13 file1Add other write & execute bit:user@host:/home/user$ chmod 647 file2user@host:/home/user$ ls -l file2-rw-r--rwx 1 user user 0 Nov 19 20:13 file2Remove group read bit:user@host:/home/user$ chmod 604 file3user@host:/home/user$ ls -l file3-rw----r-- 1 user user 0 Nov 19 20:13 file3Add read, write and execute to everyone:user@host:/home/user$ chmod 777 file4user@host:/home/user$ ls -l file4-rwxrwxrwx 1 user user 0 Nov 19 20:13 file4user@host:/home/user$chmod with sudoChanging permissions on files that you do not have ownership of: (Notethat changing permissions the wrong way on the wrong files can quickly mess up your system a great deal! Please be careful when usingsudo!)user@host:/home/user$ ls -l /usr/local/bin/somefile-rw-r--r-- 1 root root 550 2005-11-13 19:45 /usr/local/bin/somefileuser@host:/home/user$

user@host:/home/user$ sudo chmod o+x /usr/local/bin/somefile

user@host:/home/user$ ls -l /usr/local/bin/somefile-rw-r--r-x 1 root root 550 2005-11-13 19:45 /usr/local/bin/somefileuser@host:/home/user$Recursive Permission ChangesTo change the permissions of multiple files and directories with one command. Please note the warning in the chmod with sudo section and the Warning with Recursive chmod section.Recursive chmod with -R and sudoTo change all the permissions of each file and folder under a specified directory at once, use sudo chmod with -Ruser@host:/home/user$ sudo chmod 777 -R /path/to/someDirectoryuser@host:/home/user$ ls -ltotal 3-rwxrwxrwx 1 user user 0 Nov 19 20:13 file1drwxrwxrwx 2 user user 4096 Nov 19 20:13 folder-rwxrwxrwx 1 user user 0 Nov 19 20:13 file2Recursive chmod using find, pipemill, and sudoTo assign reasonably secure permissions to files and folders/directories, it's common to give files a permission of 644, and directories a 755 permission, since chmod -R assigns to both. Use sudo, the find command, and a pipemill to chmod as in the following examples.To change permission of only files under a specified directory.user@host:/home/user$ sudo find /path/to/someDirectory -type f -print0 | xargs -0 sudo chmod 644user@host:/home/user$ ls -ltotal 3-rw-r--r-- 1 user user 0 Nov 19 20:13 file1drwxrwxrwx 2 user user 4096 Nov 19 20:13 folder-rw-r--r-- 1 user user 0 Nov 19 20:13 file2To change permission of only directories under a specified directory (including that directory):user@host:/home/user$ sudo find /path/to/someDirectory -type d -print0 | xargs -0 sudo chmod 755 user@host:/home/user$ ls -ltotal 3-rw-r--r-- 1 user user 0 Nov 19 20:13 file1drwxr-xr-x 2 user user 4096 Nov 19 20:13 folder-rw-r--r-- 1 user user 0 Nov 19 20:13 file2Warning with Recursive chmodWARNING: Although it's been said, it's worth mentioning in context of a gotcha typo. Please note,Recursively deleting or chown-ing files are extremely dangerous. You will not be the first, nor the last, person to add one too many spaces into the command. This example will hose your system:user@host:/home/user$ sudo chmod -R / home/john/Desktop/tempfilesNote the space between the first / and home.You have been warned.Changing the File Owner and GroupA file's owner can be changed using thechowncommand. For example, to change thefoobarfile's owner totux:user@host:/home/user$ sudo chown tux foobarTo change thefoobarfile's group topenguins, you could useeitherchgrporchownwith special syntax:user@host:/home/user$ sudo chgrp penguins foobaruser@host:/home/user$ sudo chown :penguins foobarFinally, to change thefoobarfile's owner totuxand the group topenguinswith a single command, the syntax would be:user@host:/home/user$ sudo chown tux:penguins foobarNote that, by default, you must usesudoto change a file's owner or group.Volume Permissions with umaskThis section has been moved to:Fstab#OptionsACL (Access Control List)Posix ACLs are a way of achieving a finer granularity of permissions than is possible with the standard Unix file permissions. See the full page on ACLsFilePermissionsACLsSetting up ACL1. Install the acl package:sudo apt-get install acl2. Edit/etc/fstaband add optionaclto partition(s) on which you want to enable ACL. For example:...UUID=d027a8eb-e234-1c9f-aef1-43a7dd9a2345 /home ext4 defaults,acl 0 2...3. Remount partition(s) on which you want to enable ACL. For example:sudo mount -o remount /home4. Verifyaclis enabled on the partition(s):mount | grep aclThe commands,setfaclandgetfacl, set and read ACLs on files and directories.Example UsageThis is a simple example for use with a Samba share to ensure that any files or sub-directories created could also be modified by any Samba user.1. Create a directory with full permission:mkdir shared_dirchmod 777 shared_dir2. Set thedefaultACL with '-d' and modify with '-m' the permissions for sambanobodyusernogroupgroup which will apply to all newly created file/directories.setfacl -d -m u:nobody:rwx,g:nogroup:rwx,o::r-x shared_dirGUI ACL EditorTheEicielpackage allows GUI access to ACLs through the Nautilus file manager.Useful ACL Resources1. http://brunogirin.blogspot.com/2010/03/shared-folders-in-ubuntu-with-setgid.html2. http://wiki.kaspersandberg.com/doku.php?id=howtos:acl3. man acl4. man setfacl5. man getfaclFile removalTo remove a file you cannot delete usesudo rm -rf filenamewhere filename is the name and path of the file to delete.Nota bene:Be very careful when using the commandrmwith the-rfoption since-rmakes the file removal recursive (meaning it will remove files inside of folders) and-fwill force the removal even for files which aren't writable. To play it safe, please consider typing in the absolute path to the filesudo rm -rf /path/to/file/filenameto prevent any mishaps that can/will occur. It takes longer to type but you can't put a price on peace of mind. See thermman page for details.Sticky BitThe sticky bit applies only to directories, and is typically used on publicly-writeable directories. Within a directory upon which the sticky bit is applied, users are prevented from deleting or renaming any files that they do not personally own.To add or remove the sticky bit, use chmod with the "t" flag:chmod +t chmod -t The status of the sticky bit is shown in the other execute field, when viewing the long output of ls. "t" or "T" in the other execute field indicates the sticky bit is set, anything else indicates it is not.Making a public directory:user@host:/home/user$ mkdir folderuser@host:/home/user$ chmod 777 folderuser@host:/home/user$ ls -ltotal 3drwxrwxrwx 2 user user 4096 Nov 19 20:13 folderAdding the sticky bit (note the "t" in the other execute field):user@host:/home/user$ chmod +t folderuser@host:/home/user$ ls -ltotal 3drwxrwxrwt 2 user user 4096 Nov 19 20:13 folder

FindingFiles

Command LineThere are a number of command line tools to help you find a file on system.apt-fileThe first method is for finding files that are (or should be) provided by Ubuntu's packages. If you're not familiar with the file being complained about, odds are good that it falls into this category. The apt packaging system is aware of almost all the files it provides and can be queried to learn what package provides a given file and where that file is (or should be). To take advantage of this feature, install the packageapt-fileand then runapt-fileupdatein a terminal.Now, say you've been trying to compile a new kernel module, and its build system complains at you that there's "No such file or directory - version.h" or some such. You could "apt-file search version.h", but that would be a pretty broad search and would return such files as subversion.html. You can guess that this file has something to do with the kernel, and I happen to know that in a fully prepped kernel tree, it should be found in a directory called "linux", so I say "apt-file search linux/version.h" and find just what I was looking for: which package I need to install to have the file I need. See the apt-file man page for some handy options like case-insensitive searching and regular expression matching.dpkg -LMaybe you suspect that the file in question is supposed to be provided by the same package you're working with.dpkg -L will show you a list of files provided by that package. For example, you've just installed kxdocker_0.32-1_i386.deb and your first guess, "kxdocker", doesn't run the program.$ kxdocker-bash: kxdocker: command not foundWell it's in there somewhere:$ dpkg -L kxdocker | grep bin/usr/local/kde/bin/usr/local/kde/bin/kxdockerAh, it's there, but /usr/local/kde/bin isn't in your $PATH. Now you know that you can add it to your $PATH or run the command with the full path.dpkg -SSometimes you might want to find out which package provides a certain file.dpkg -S /full/path/to/filewill show you the package.For example,dpkg -S /usr/bin/gnome-keybindings-propertiesgnome-control-center: /usr/bin/gnome-keybinding-propertiestells you that gnome-keybinding-properties is provided by the package gnome-control-center.findThe Unix command "find" is quite powerful, and if you know how to use it you can find pretty well anything. The basic syntax is "find ". Options include criteria for your search, actions to take on files found, etc. I'll give you a couple of examples then point you to the man page for detailed usage and more interesting examples.You want to find every file in ~/mydir and all its subdirectories, recursively, with a file extension of .htm (or .HTM or .Htm...) and delete it. I've seen a lot of attempts like rm -rf ~/mydir/*.htm which really don't come close. The correct solution isfind ~/mydir -iname '*.htm' -exec rm {} \;"-iname" says that you want to do a case-insensitive search on the filename. '*.htm' is in single quotes to prevent bash from expanding the *, which will produce unexpected results. The rest of the command says to remove any file matching the query. The "{}" will be replaced by the filename (with path) returned by the search, and "\;" will separate one rm command from the next. Nearly every -exec option should be terminated with a "\;".Now you want to fix permissions. For some reason, there seem to be directories in your home directory that you don't have permission to enter. You know that the operative bit for directories is the execute bit. You know that "chmod -R +x ~" will add the execute bit to every file and directory in ~ (or $HOME), but you only want to operate on directories - BritneySpearsOopsIDidItAgain.avi doesn't need to be executable. This is solved with:find ~ -type d -exec chmod +x {} \;where "-type d" of course means directories.Finally, you want to make a playlist out of all the mp3 and ogg files in your home directory.find ~ -type f \( -iname '*.mp3' -o -iname '*.ogg' \) > mynewplaylist.m3uWe group the -iname parameters in parentheses and separate them with -o (the "OR" operator) to say that any match must be a file, AND it must be named .mp3 OR .ogg (case-insensitive) to be returned. We redirect the output to a new file called mynewplaylist.m3u, and presto! We have a playlist.locateOh, where did I put that file? I've got directories and partitions all over the computer where I put files, and they're not quite well-organized enough for me to figure out where I put resume.doc last year when I was job-hunting. I don't want to use "find" because it'll take forever to search my entire computer. I can't use apt-file because resume.doc is not provided by any Ubuntu package. Thankfully my computer indexes all my files every night while I sleep and I can search just the index, which will take only a few seconds, even on as an expansive a filesystem as mine. Of course the software needs to be installed ("sudo apt-get install slocate"). If I look at root's cron jobs ("sudo crontab -e") I see that the slocate package has been faithfully updating my index02 4 * * * /usr/bin/updatedb -e /mnt/data,/mnt/filesevery night at 4:02am, excluding /mnt/data and /mnt/files, which are remote Samba mounts that I prefer not to index. So as long as my resume is on one of my local mounted filesystems, I should be able to find it.locate resume.docIt's that simple, unless I'm not quite sure about the spelling, in which case I might use -i for a case-insensitive search or -r to use a POSIX regular expression.which and whereisTwo more commands that occasionally come in handy are "which" and "whereis". "which" will search your $PATH ("echo $PATH") for a given command and return the first match - the one that will be run if you specify the command without a path. "whereis" will return any and all binaries, sources and man pages associated with the argument you give it. "which" can come in handy for example if you've installed the same software via apt-get and again from source. Very likely you'll have the same command in two different places, and "which" can help you figure out why the version you thought you updated to isn't running. If you have "xchat" in both /usr/bin and /usr/local/bin, "which" will tell you what will happen when you just run "xchat". "whereis" will show you both, plus any man pages and (depending on the circumstances) the source tree from which you compiled it.Gnome, KDE etc. have numerous utilities for finding files, and their usage is left as an exercise for the reader. Learn how to use these commands effectively and I predict you'll forget those graphical utilities ever existed.

AptGet/Howto

Introduction to APT"In the beginning there was the .tar.gz. Users had to compile each program that they wanted to use on their GNU/Linux systems. When Debian was created, it was deemed necessary that the system include a method of managing the packages installed on the machine. The name dpkg was given to this system. Thus the famous 'package' first came into being on GNU/Linux, a while before Red Hat decided to create their own 'rpm' system.A new dilemma quickly took hold of the minds of the makers of GNU/Linux. They needed a rapid, practical, and efficient way to install packages that would manage dependencies automatically and take care of their configuration files while upgrading. Here again, Debian led the way and gave birth to APT, the Advanced Packaging Tool, which has since been ported by Conectiva for use with rpm and has been adopted by some other distributions."1. -- From Debian APT HOWTOCommandsAll of these commands must be run as root or with superuser privileges, seesudofor more information. Replace with the name of the package you are attempting to install.

1. sudo apt-get install ubuntu-desktop Installation commands1. apt-get install This command installs a new package.2. apt-get build-dep This command searches the repositories and installs the build dependencies for . If the package is not in the repositories it will return an error.3. aptitude install Aptitude is anNcursesviewer of packages installed or available. Aptitude can be used from the command line in a similar way to apt-get. Seemanaptitudefor more information.4. APT and aptitude will accept multiple package names as a space delimited list. For example:apt-get install Use the -s flag to simulate an action."sudo apt-get -s install " will simulate installing the package showing you what packages will be installed and configured.

auto-apt1. auto-apt run When invoked, the auto-apt command automatically installs packages upon missing file access. If a program tries to access a file known to belong in an uninstalled package, auto-apt will install that package using apt-get. This feature requiresaptandsudoto work.2. Auto-apt keeps databases which need to be kept up-to-date in order for it to be effective. This is achieved by calling the commands auto-apt update, auto-apt updatedb and auto-apt update-local.3. Usage example1. You're compiling a program and, all of a sudden, there's an error because it needs a file you don't have. The program auto-apt asks you to install packages if they're needed, stopping the relevant process and continuing once the package is installed. # auto-apt run ./configureIt will then ask to install the needed packages and call apt-get automatically. If you're running X, a graphical interface will replace the default text interface.Maintenance commands1. apt-get updateRun this command after changing/etc/apt/sources.listor/etc/apt/preferences. For information regarding/etc/apt/preferences, seePinningHowto. Run this command periodically to make sure your source list is up-to-date. This is the equivalent of "Reload" in Synaptic or "Fetch updates" in Adept.2. apt-get upgradeThis command upgrades all installed packages. This is the equivalent of "Mark all upgrades" in Synaptic.3. apt-get dist-upgradeThe same as the above, except add the "smart upgrade" checkbox. It tells APT to use "smart" conflict resolution system, and it will attempt to upgrade the most important packages at the expense of less important ones if necessary."apt-get dist-upgrade" does not perform distribution upgrade. See [http://www.ubuntu.com/getubuntu/upgradingupgrading] for more information.

4. apt-get checkThis command is a diagnostic tool. It does an update of the package lists and checks for broken dependencies.5. apt-get -f installThis command does the same thing asEdit->Fix Broken Packagesin Synaptic. Do this if you get complaints about packages with "unmet dependencies".6. apt-get autocleanThis command removes .deb files for packages that are no longer installed on your system. Depending on your installation habits, removing these files from/var/cache/apt/archivesmay regain a significant amount of diskspace.7. apt-get cleanThe same as above, except it removesallpackages from the package cache. This may not be desirable if you have a slow Internet connection, since it will cause you to redownload any packages you need to install a program.1. The package cache is in/var/cache/apt/archives. The commanddu -sh /var/cache/apt/archiveswill tell you how much space cached packages are consuming.8. dpkg-reconfigure Reconfigure the named package. With many packages, youll be prompted with some configuration questions you may not have known were there.1. For example:dpkg-reconfigure fontconfig-configwill present you with a "wizard" on configuring fonts in Ubuntu.9. echo " hold" | dpkg --set-selectionsThis command places the desired package on hold.1. This command may have the unintended side effect of preventing upgrades to packages that depend on updated versions of the pinned package.apt-getdist-upgradewill override this, but will warn you first. If you want to use this command with sudo, you need to useecho"hold"|sudodpkg--set-selectionsnotsudoecho"hold"|dpkg--set-selections.

10. echo " install" | dpkg --set-selectionsThis command removes the "hold" or "locked package" state set by the above command. The note above about sudo usage applies to this command.Removal commands1. apt-get remove This command removes an installed package, leaving configuration files intact.2. apt-get purge This command completely removes a package and the associated configuration files. Configuration files residing in ~ are not usually affected by this command.1. + operator1. If you want to remove package1 and install package2 in one step:apt-get remove +.3. apt-get autoremoveThis command removes packages that were installed by other packages and are no longer needed.1. apt-get autoremove This command removes an installed package and dependencies.4. While there is no built in way to remove all of your configuration information from your removed packages you can remove all configuration data from every removed package with the following command.dpkg -l | grep '^rc' | awk '{print $2}' | xargs dpkg --purgeSearch commands1. apt-cache search This command will find packages that include .2. dpkg -l **This will find packages whose names contain . Similar toapt-cachesearch, but also shows whether a package is installed on your system by marking it withii(installed) andun(not installed).3. apt-cache show This command shows the description of package and other relevant information including version, size, dependencies and conflicts.4. dpkg --print-avail This command is similar to "apt-cache show".5. dpkg -L This command will list files in package .6. dpkg -c foo.debThis command lists files in the package "foo.deb". Note thatfoo.debis apathname. Use this command on .deb packages that you have manually downloaded.7. dlocate This command determines which installed package owns . It shows files from installed packages that match , with the name of the package they came from. Consider this to be a "reverse lookup" utility.In order to use this command, the packagedlocatemust be installed on your system.

8. dpkg -S This command does the same asdlocate, but does not require the installation of any additional packages. It is slower thandlocatebut has the advantage of being installed by default on all Debian and Ubuntu systems.9. apt-file search This command acts like dlocate and dpkg -S, but searches all available packages. It answers the question, "what package provides this file?".1. apt-file needs to be updated regularly like apt-get. Use the command:apt-file updateIn order to use this command, the packageapt-filemust be installed on your system.

10. apt-cache pkgnamesThis command provides a listing of every package in the system11. A general note on searching: If searching for a generates a list that is too long, you can filter your results by piping them through the commandgrep. Examples:1. apt-cache search filename | grep -w filenamewill show only the files that contain filename as a whole word2. dpkg -L package | grep /usr/bin will list files located in the directory /usr/bin, useful if you're looking for a particular executable.For more information on apt-get, apt-cache and dpkg consult their manual pages by using themancommand. These manuals will provide a wider scope of information in addition to all of the options that you can use with each program.1. Example:man apt-get.Typical usage exampleI want to feel the wind in my hair, I want the adrenaline of speed. So lets install a racing game. But what racing games are available?apt-cache search racing gameIt gives me a lot of answers. I see a game named "torcs". Lets get some more information on this game.apt-cache show torcsHmmm... it seems interesting. But is this game not already installed on my computer? And what is the available version? Is it from Universe or main?apt-cache policy torcsOk, so now, let's install it!apt-get install torcsWhat is the command I must type in the console to launch this game? In this example, it's straightforward ("torcs"), but that's not always the case. One way of finding the name of the binary is to look at what files the package has installed in "/usr/bin". For games, the binary will be in "/usr/games". For administrative programs, it's in "/usr/sbin".dpkg -L torcs | grep /usr/games/The first part of the command display all files installed by the package "torcs" (try it). With the second part, we ask to only display lines containing "/usr/games/".Hmmm, that game is cool. Maybe there are some extra tracks?apt-cache search torcsBut I'm running out of space. I will delete the apt cache!apt-get cleanOh no, my mother asked me to remove all games from this computer. But I want to keep the configuration files so I can simply re-install it later.apt-get remove torcsIf I want to also remove config files :apt-get purge torcs

RootSudo

Background InformationIn Linux (and Unix in general), there is a SuperUser namedRoot. The Windows equivalent of Root is Administrators group. The SuperUser can do anything and everything, and thus doing daily work as the SuperUser can be dangerous. You could type a command incorrectly and destroy the system. Ideally, you run as a user that has only the privileges needed for the task at hand. In some cases, this is necessarily Root, but most of the time it is a regular user.By default, the Root account password is locked in Ubuntu.This means that you cannot login as Root directly or use thesucommand to become the Root user. However, since the Root account physically exists it is still possible to run programs with root-level privileges. This is wheresudocomes in - it allows authorized users (normally "Administrative" users; for further information please refer toAddUsersHowto) to run certain programs as Root without having to know the root password.This means that in theterminalyou should use sudo for commands that require root privileges; simply prependsudoto all the commands you would normally run as Root. For more extensive usage examples, please see below. Similarly, when you run GUI programs that require root privileges (e.g. the network configuration applet), use graphical sudo and you will also be prompted for a password (more below). Just remember, when sudo asks for a password, it needsYOUR USER password, and not the Root account password.Please keep in mind, a substantial number of Ubuntu users are new to Linux.There is a learning curve associated with any OS and many new users try to take shortcuts by enabling the root account, logging in as root, and changing ownership of system files.Example:Broken system via (ab)use of root by a new userPlease note: At the time of the post, this was the users first post on the Ubuntu forums. While some may say this is a "learning experience", learning by breaking your system is frustrating and can result in data loss.When giving advice on the Ubuntu Forums and IRC, please take the time to teach "the basics" such as ownership, permissions, and how to use sudo / gksu / kdesudo in such a way that new users do not break systems.Advantages and DisadvantagesBenefits of using sudoSome benefits of leavingRootlogins disabled by default include the following:1. The Ubuntu installer has fewer questions to ask.2. Users don't have to remember an extra password (i.e. the root password), which they are likely to forget (or write down so anyone can crack into their account easily).3. It avoids the "I can doanything" interactive login by default (e.g. the tendency by users to login as an "Administrator" user in Microsoft Windows systems), you will be prompted for a password before major changes can happen, which should make you think about the consequences of what you are doing.4. sudo adds a log entry of the command(s) run (in/var/log/auth.log). If you mess up, you can always go back and see what commands were run. It is also nice for auditing.5. Every cracker trying tobrute-forcetheir way into your box will know it has an account namedRootand will try that first. What they don't know is what the usernames of your other users are. Since the Root account password is locked, this attack becomes essentially meaningless, since there is no password to crack or guess in the first place.6. Allows easy transfer for admin rights, in a short term or long term period, by adding and removing users from groups, while not compromising theRootaccount.7. sudo can be setup with a much more fine-grained security policy.8. The Root account password does not need to be shared with everybody who needs to perform some type of administrative task(s) on the system (see the previous bullet).9. The authentication automatically expires after a short time (which can be set to as little as desired or 0); so if you walk away from the terminal after running commands as Root using sudo, you will not be leaving a Root terminal open indefinitely.Downsides of using sudoAlthough for desktops the benefits of using sudo are great, there are possible issues which need to be noted:1. Redirecting the output of commands run with sudo requires a different approach. For instance considersudols>/root/somefilewill not work since it is the shell that tries to write to that file. You can usels|sudotee-a/root/somefileto append, orls|sudotee/root/somefileto overwrite contents. You could also pass the whole command to a shell process run under sudo to have the file written to with root permissions, such assudosh-c"ls>/root/somefile".2. In a lot of office environments the ONLY local user on a system is Root. All other users are imported using NSS techniques such as nss-ldap. To setup a workstation, or fix it, in the case of a network failure where nss-ldap is broken, Root is required. This tends to leave the system unusable unless cracked. An extra local user, or an enabled Root password is needed here. The local user account should have its $HOME on a local disk, _not_ on NFS (or any other networked filesystem), and a .profile/.bashrc that doesn't reference any files on NFS mounts. This is usually the case for Root, but if adding a non-Root rescue account, you will have to take these precautions manually.1. Alternatively, a sysadmin type account can be implemented as a local user on all systems, and granted proper sudo privileges. As explained in the benefits section above, commands can be easily tracked and audited.Usage1. When using sudo, your password is stored by default for 15 minutes. After that time, you will need to enter your password again.2. Your password willnotbe shown on the screen as you type it, not even as a row of stars (******). It is being entered with each keystroke!sudoTo usesudoon the command line, preface the command withsudo, as below:Example #1sudo chown bob:bob /home/bob/*Example #2sudo /etc/init.d/networking restartTo repeat the last command entered, except with sudo prepended to it, run:sudo !!

UsersAllowing other users to run sudoTo add a new user to sudo, open theUsers and Groupstool fromSystem->Administrationmenu. Then click on the user and then on properties. Choose theUser Privilegestab. In the tab, findAdminister the systemand check that.1. In Hardy Heron and newer, you must firstUnlock, then you can select a user from the list and hitProperties. Choose theUser Privilegestab and checkAdminister the system.In the terminal (for Precise Pangolin, 12.04), this would be:sudo adduser sudowhere you replace with the name of the user (without the ).In previous version of Ubuntusudo adduser adminwould have been appropriate, but the admin group has been deprecated and no longer exists in Ubuntu 12.04.Logging in as another userPlease don't use this to become Root,see further down in the page for more information about that.sudo -i -u For example to become the useramandafor tape management purposes.sudo -i -u amandaThe password being asked for is your own, not amanda's.root accountEnabling the root accountEnabling the Root account is rarely necessary. Almost everything you need to do as administrator of an Ubuntu system can be done via sudo or gksudo. If you really need a persistent Root login, the best alternative is to simulate a Root login shell using the following command...

sudo -iTo enable the Root account (i.e. set a password) use:sudo passwd rootUse at your own risk!Logging in to X as root may cause very serious trouble.If you believe you need a root account to perform a certain action,please consult the official support channels first, to make sure there is not a better alternative.

Re-disabling your root accountIf for some reason you have enabled your root account and wish to disable it again, use the following command in terminal...

sudo passwd -dl root

Remove Password Prompt For sudoIf you disable the sudo password for your account, you will seriously compromise the security of your computer. Anyone sitting at your unattended, logged in account will have complete Root access, and remote exploits become much easier for malicious crackers.

1. This method is NOT suggested nor supported by the designers of Ubuntu.2. Please do not suggest this to others unless you personally are available 24/7 to support the user if they have issues as a result of running a shell as Root.These instructions are to remove the prompt for a password when using thesudocommand.Thesudocommand will still need to be used for Root access though.Edit the sudoers fileOpen a Terminal window.Type insudo visudo.Add the following line to the END of the file (if not at the end it can be nullified by later entries): ALL=NOPASSWD: ALLReplace with your user name (without the ). This is assuming that Ubuntu has created a group with the same name as your user name, which is typical. You can alternately use the groupusersor any other such group you are in. Just make sure you are in that group. This can be checked by going toSystem->Administration->Users and GroupsExample:michael ALL=NOPASSWD: ALLType in^xto exit.This should prompt for an option to save the file, type inYto save.Log out, and then log back in. This should now allow you to run the sudo command without being prompted for a password.Or to do this for the system wide groupsudoroot$ echo "%sudo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoersLog out, and then back in.

What is "the shell"?Simply put, the shell is a program that takes your commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix computer. Nowadays, we havegraphical user interfaces (GUIs)in addition tocommand line interfaces (CLIs)such as the shell.On most Linux systems a program calledbash(which stands for Bourne Again SHell, an enhanced version of the original Bourne shell program,sh, written by Steve Bourne) acts as the shell program. There are several additional shell programs available on a typical Linux system. These include:ksh,tcshandzsh.What's an xterm, gnome-terminal, konsole, etc.?These are called "terminal emulators." They are programs that put a window up and let you interact with the shell. There are a bunch of different terminal emulators you can use. Most Linux distributions supply several, such as:xterm,rxvt,konsole,kvt,gnome-terminal,nxterm, andeterm.Starting a TerminalYour window manager probably has a way to launch programs from a menu. Look through the list of programs to see if anything looks like a terminal emulator program. In KDE, you can find "konsole" and "terminal" on the Utilities menu. In Gnome, you can find "color xterm," "regular xterm," and "gnome-terminal" on the Utilities menu. You can start up as many of these as you want and play with them. While there are a number of different terminal emulators, they all do the same thing. They give you access to a shell session. You will probably develop a preference for one, based on the different bells and whistles each one provides.Testing the KeyboardOk, let's try some typing. Bring up a terminal window. You should see a shell prompt that contains your user name and the name of the machine followed by a dollar sign. Something like this:[me@linuxbox me]$Excellent! Now type some nonsense characters and press the enter key.[me@linuxbox me]$kdkjflajfksIf all went well, you should have gotten an error message complaining that it cannot understand you:[me@linuxbox me]$kdkjflajfksbash: kdkjflajfks: command not foundWonderful! Now press the up-arrow key. Watch how our previous command "kdkjflajfks" returns. Yes, we havecommand history. Press the down-arrow and we get the blank line again.Recall the "kdkjflajfks" command using the up-arrow key if needed. Now, try the left and right-arrow keys. You can position the text cursor anywhere in the command line. This allows you to easily correct mistakes.You're not logged in as root, are you?Don't operate the computer as the superuser. You should only become the superuser when absolutely necessary. Doing otherwise is dangerous, stupid, and in poor taste. Create a user account for yourself now!Using the MouseEven though the shell is a command line interface, you can still use the mouse for several things. That is, if you have a 3-button mouse; and you should have a 3-button mouse if you want to use Linux.First, you can use the mouse to scroll backwards and forwards through the output of the terminal window. To demonstrate, hold down the enter key until it scrolls off the window. Now, with your mouse, you can use the scroll bar at the side of the terminal window to move the window contents up and down. If you are usingxterm, you may find this difficult, since the middle button is required for this operation. If you have a 2-button mouse, it may have been configured to emulate a 3-button mouse. This means the middle button can be simulated by pressing down both the left and right buttons at the same time.Next, you can copy text with the mouse. Drag your mouse over some text (for example, "kdkjflajfks" right here on the browser window) while holding down the left button. The text should highlight. Now move your mouse pointer to the terminal window and press the middle mouse button. The text you highlighted in the browser window should be copied into the command line. Did I mention that you will need a 3-button mouse?A few words about focus...When you installed your Linux system and its window manager (most likely Gnome or KDE), it was configured to behave in some ways like that legacy operating system.In particular, it probably has itsfocus policyset to "click to focus." This means that in order for a window to gain focus (become active) you have to click in the window. This is contrary to traditional X windows behavior. If you take my advice and get a 3-button mouse, you will want to set the focus policy to "focus follows mouse". This will make using the text copying feature of X windows much easier to use. You may find it strange at first that windows don't raise to the front when they get focus (you have to click on the title bar to do that), but you will enjoy being able to work on more than one window at once without having the active window obscuring the the other. Try it and give it a fair trial; I think you will like it. You can find this setting in the configuration tools for your window manager.

NavigationIn this lesson, I will introduce your first three commands:pwd(print working directory),cd(change directory), andls(list files and directories).If you have not worked with a command line interface before, you will need to pay close attention to this lesson, since the concepts will take some getting used to.File System OrganizationLike that legacy operating system, the files on a Linux system are arranged in what is called ahierarchical directory structure. This means that they are organized in a tree-like pattern of directories (called folders in other systems), which may contain files and other directories. The first directory in the file system is called theroot directory. The root directory contains files and subdirectories, which contain more files and subdirectories and so on and so on.Most graphical environments today include a file manager program to view and manipulate the contents of the file system. Often you will see the file system represented like this:

One important difference between the legacy operating system and Unix/Linux is that Linux does not employ the concept of drive letters. While drive letters split the file system into a series of different trees (one for each drive), Linux always has a single tree. Different storage devices may contain different branches of the tree, but there is always a single tree.pwdSince a command line interface cannot provide graphic pictures of the file system structure, it must have a different way of representing it. Think of the file system tree as a maze, and you are standing in it. At any given moment, you stand in a single directory. Inside that directory, you can see its files and the pathway to its parent directory and the pathways to the subdirectories of the directory in which you are standing.The directory you are standing in is called theworking directory. To find the name of the working directory, use thepwdcommand.[me@linuxbox me]$pwd/home/meWhen you first log on to a Linux system, the working directory is set to your home directory. This is where you put your files. On most systems, your home directory will be called /home/your_user_name, but it can be anything according to the whims of the system administrator.To list the files in the working directory, use thelscommand.[me@linuxbox me]$ls

Desktop Xrootenv.0 linuxcmdGNUstep bin nedit.rpmGUILG00.GZ hitni123.jpg nsmail

I will come back tolsin the next lesson. There are a lot of fun things you can do with it, but I have to talk about pathnames and directories a bit first.cdTo change your working directory (where you are standing in the maze) you use thecdcommand. To do this, typecdfollowed by thepathnameof the desired working directory. A pathname is the route you take along the branches of the tree to get to the directory you want. Pathnames can be specified in one of two different ways;absolute pathnamesorrelative pathnames. Let's deal with absolute pathnames first.An absolute pathname begins with the root directory and follows the tree branch by branch until the path to the desired directory or file is completed. For example, there is a directory on your system in which programs are installed for the X window system. The pathname of the directory is /usr/X11R6/bin. This means from the root directory (represented by the leading slash in the pathname) there is a directory called "usr" which contains a directory called "X11R6" which contains a directory called "bin".Let's try this out:[me@linuxbox me]$cd /usr/X11R6/bin[me@linuxbox bin]$pwd/usr/X11R6/bin[me@linuxbox bin]$lsAnimate import xfwpAnotherLevel lbxproxy xg3Audio listres xgalAuto lndir xgammonBanner makedepend xgcCascade makeg xgetfileClean mergelib xgopherForm mkdirhier xhexagonsIdent mkfontdir xhostPager mkxauth xieperfPager_noxpm mogrify xinitRunWM montage xitermRunWM.AfterStep mtv xjewelRunWM.Fvwm95 mtvp xkbbellRunWM.MWM nxterm xkbcomp

and many more...

Now we can see that we have changed the current working directory to /usr/X11R6/bin and that it is full of files. Notice how your prompt has changed? As a convenience, it is usually set up to display the name of the working directory.Where an absolute pathname starts from the root directory and leads to its destination, a relative pathname starts from the working directory. To do this, it uses a couple of special symbols to represent relative positions in the file system tree. These special symbols are "." (dot) and ".." (dot dot).The "." symbol refers to the working directory and the ".." symbol refers to the working directory's parent directory. Here is how it works. Let's change the working directory to /usr/X11R6/bin again:[me@linuxbox me]$cd /usr/X11R6/bin[me@linuxbox bin]$pwd/usr/X11R6/binO.K., now let's say that we wanted to change the working directory to the parent of /usr/X11R6/bin which is /usr/X11R6. We could do that two different ways. First, with an absolute pathname:[me@linuxbox bin]$cd /usr/X11R6[me@linuxbox X11R6]$pwd/usr/X11R6Or, with a relative pathname:[me@linuxbox bin]$cd ..[me@linuxbox X11R6]$pwd/usr/X11R6Two different methods with identical results. Which one should you use? The one that requires less typing!Likewise, we can change the working directory from /usr/X11R6 to /usr/X11R6/bin in two different ways. First using an absolute pathname:[me@linuxbox X11R6]$cd /usr/X11R6/bin[me@linuxbox bin]$pwd/usr/X11R6/binOr, with a relative pathname:[me@linuxbox X11R6]$cd ./bin[me@linuxbox bin]$pwd/usr/X11R6/binNow, there is something important that I must point out here. In almost all cases, you can omit the "./". It is implied. Typing:[me@linuxbox X11R6]$cd binwould do the same thing. In general, if you do not specify a pathname to something, the working directory will be assumed. There is one important exception to this, but we won't get to that for a while.A couple of shortcutsIf you typecdfollowed by nothing,cdwill change the working directory to your home directory.A related shortcut is to typecd ~user_name. In this case,cdwill change the working directory to the home directory of the specified user.Important facts about file names1. File names that begin with a period character are hidden. This only means thatlswill not list them unless you sayls -a. When your account was created, several hidden files were placed in your home directory to configure things for your account. Later on we will take a closer look at some of these files to see how you can customize your environment. In addition, some applications will place their configuration and settings files in your home directory as hidden files.2. File names in Linux, like Unix, are case sensitive. The file names "File1" and "file1" refer to different files.3. Linux has no concept of a "file extension" like legacy operating systems. You may name files any way you like. The contents/purpose of a file is determined by other means.4. While Linux supports long file names which may contain embedded spaces and punctuation characters, limit the punctuation characters to period, dash, and underscore.Most importantly, do not embed spaces in file names.If you want to represent spaces between words in a file name, use underscore characters. You will thank yourself later.

Looking AroundNow that you know how to move from working directory to working directory, we're going to take a tour of your Linux system and, along the way, learn some things about what makes it tick. But before we begin, I have to teach you some tools that will come in handy during our adventure. These are: ls(list files and directories) less(view text files) file(classify a file's contents)lsThelscommand is used to list the contents of a directory. It is probably the most commonly used Linux command. It can be used in a number of different ways. Here are some examples:Examples of the ls command

CommandResult

lsList the files in the working directory

ls /binList the files in the /bin directory (or any other directory you care to specify)

ls -lList the files in the working directory in long format

ls -l /etc /binList the files in the /bin directory and the /etc directory in long format

ls -la ..List all files (even ones with names beginning with a period character, which are normally hidden) in the parent of the working directory in long format

These examples also point out an important concept about commands. Most commands operate like this: command -options argumentswherecommandis the name of the command,-optionsis one or more adjustments to the command's behavior, andargumentsis one or more "things" upon which the command operates.In the case ofls, we see thatlsis the name of the command, and that it can have one or more options, such as-aand-l, and it can operate on one or more files or directories.A Closer Look At Long FormatIf you use the-loption withls, you will get a file listing that contains a wealth of information about the files being listed. Here's an example:

-rw------- 1 bshotts bshotts 576 Apr 17 1998 weather.txtdrwxr-xr-x 6 bshotts bshotts 1024 Oct 9 1999 web_page-rw-rw-r-- 1 bshotts bshotts 276480 Feb 11 20:41 web_site.tar-rw------- 1 bshotts bshotts 5743 Dec 16 1998 xmas_file.txt

---------- ------- ------- -------- ------------ ------------- | | | | | | | | | | | File Name | | | | | | | | | +--- Modification Time | | | | | | | +------------- Size (in bytes) | | | | | +----------------------- Group | | | +-------------------------------- Owner | +---------------------------------------------- File Permissions

File NameThe name of the file or directory.Modification TimeThe last time the file was modified. If the last modification occurred more than six months in the past, the date and year are displayed. Otherwise, the time of day is shown.SizeThe size of the file in bytes.GroupThe name of the group that has file permissions in addition to the file's owner.OwnerThe name of the user who owns the file.File PermissionsA representation of the file's access permissions. The first character is the type of file. A "-" indicates a regular (ordinary) file. A "d" indicates a directory. The second set of three characters represent the read, write, and execution rights of the file's owner. The next three represent the rights of the file's group, and the final three represent the rights granted to everybody else.lesslessis a program that lets you view text files. This is very handy since many of the files used to control and configure Linux are human readable (as opposed to the legacy operating systems).What is "text"?There are many ways to represent information on a computer. All methods involve defining a relationship between the information and some numbers that will be used to represent it. Computers, after all, only understand numbers and all data is converted to numeric representation.Some of these representation systems are very complex (such as compressed image files), while others are rather simple. One of the earliest and simplest is calledASCII text.ASCII(pronounced "As-Key") is short for American Standard Code for Information Interchange. This is a simple encoding scheme that was first used on Teletype machines to map keyboard characters to numbers.Text is a simple one-to-one mapping of characters to numbers. It is very compact. Fifty characters of text translates to fifty bytes of data. Throughout a Linux system, many files are stored in text format and there are many Linux tools that work with text files. Even the legacy operating systems recognize the importance of this format. The well-known NOTEPAD.EXE program is an editor for plain ASCII text files.Thelessprogram is invoked by simply typing:less text_file

This will display the file.Controlling lessOnce started,lesswill display the text file one page at a time. You may use the Page Up and Page Down keys to move through the text file. To exitless, type "q". Here are some commands thatlesswill accept:Keyboard commands for the less program

CommandAction

Page Up or bScroll back one page

Page Down or spaceScroll forward one page

GGo to the end of the text file

1GGo to the beginning of the text file

/charactersSearch forward in the text file for an occurence of the specifiedcharacters

nRepeat the previous search

qQuit

fileAs you wander around your Linux system, it is helpful to determine what a file contains before you try to view it. This is where thefilecommand comes in.filewill examine a file and tell you what kind of file it is.To use thefileprogram, just type:file name_of_file

Thefileprogram can recognize most types of files, such as:Various kinds of files

File TypeDescriptionViewable as text?

ASCII textThe name says it allyes

Bourne-Again shell script textAbashscriptyes

ELF 32-bit LSB core fileA core dump file (a program will create this when it crashes)no

ELF 32-bit LSB executableAn executable binary programno

ELF 32-bit LSB shared objectA shared libraryno

GNU tar archiveA tape archive file. A common way of storing groups of files.no, usetar tvfto view listing.

gzip compressed dataAn archive compressed withgzipno

HTML document textA web pageyes

JPEG image dataA compressed JPEG imageno

PostScript document textA PostScript fileyes

RPMA Red Hat Package Manager archiveno, userpm -qto examine contents.

Zip archive dataAn archive compressed withzipno

While it may seem that most files cannot be viewed as text, you will be surprised how many can. This is especially true of the important configuration files. You will also notice during our adventure that many features of the operating system are controlled by shell scripts. In Linux, there are no secrets!

A Guided TourIt's time to take our tour. The table below lists some interesting places to explore. This is by no means a complete list, but it should prove to be an interesting adventure. For each of the directories listed below, do the following: cdinto each directory. Uselsto list the contents of the directory. If you see an interesting file, use thefilecommand to determine its contents. For text files, uselessto view them.Interesting directories and their contents

DirectoryDescription

/The root directory where the file system begins. In most cases the root directory only contains subdirectories.

/bootThis is where the Linux kernel and boot loader files are kept. The kernel is a file calledvmlinuz.

/etcThe/etcdirectory contains the configuration files for the system. All of the files in/etcshould be text files. Points of interest:/etc/passwdThepasswdfile contains the essential information for each user. It is here that users are defined./etc/fstabThefstabfile contains a table of devices that get mounted when your system boots. This file defines your disk drives./etc/hostsThis file lists the network host names and IP addresses that are intrinsically known to the system./etc/init.dThis directory contains the scripts that start various system services typically at boot time.

/bin, /usr/binThese two directories contain most of the programs for the system. The/bindirectory has the essential programs that the system requires to operate, while/usr/bincontains applications for the system's users.

/sbin, /usr/sbinThesbindirectories contain programs for system administration, mostly for use by the superuser.

/usrThe/usrdirectory contains a variety of things that support user applications. Some highlights:/usr/share/X11Support files for the X Windows system/usr/share/dictDictionaries for the spelling checker. Bet you didn't know that Linux had a spelling checker. Seelookandispell./usr/share/docVarious documentation files in a variety of formats./usr/share/manThe man pages are kept here./usr/srcSource code files. If you installed the kernel source code package, you will find the entire Linux kernel source code here.

/usr/local/usr/localand its subdirectories are used for the installation of software and other files for use on the local machine. What this really means is that software that is not part of the official distribution (which usually goes in/usr/bin) goes here.

When you find interesting programs to install on your system, they should be installed in one of the/usr/localdirectories. Most often, the directory of choice is/usr/local/bin.

/varThe/vardirectory contains files that change as the system is running. This includes:/var/logDirectory that contains log files. These are updated as the system runs. You should view the files in this directory from time to time, to monitor the health of your system./var/spoolThis directory is used to hold files that are queued for some process, such as mail messages and print jobs. When a user's mail first arrives on the local system (assuming you have local mail), the messages are first stored in/var/spool/mail

/libThe shared libraries (similar to DLLs in that other operating system) are kept here.

/home/homeis where users keep their personal work. In general, this is the only place users are allowed to write files. This keeps things nice and clean :-)

/rootThis is the superuser's home directory.

/tmp/tmpis a directory in which programs can write their temporary files.

/devThe/devdirectory is a special directory, since it does not really contain files in the usual sense. Rather, it contains devices that are available to the system. In Linux (like Unix), devices are treated like files. You can read and write devices as though they were files. For example/dev/fd0is the first floppy disk drive,/dev/sda(/dev/hdaon older systems) is the first IDE hard drive. All the devices that the kernel understands are represented here.

/procThe/procdirectory is also special. This directory does not contain files. In fact, this directory does not really exist at all. It is entirely virtual. The/procdirectory contains little peep holes into the kernel itself. There are a group of numbered entries in this directory that correspond to all the processes running on the system. In addition, there are a number of named entries that permit access to the current configuration of the system. Many of these entries can be viewed. Try viewing/proc/cpuinfo. This entry will tell you what the kernel thinks of your CPU.

/media,/mntFinally, we come to/media, a normal directory which is used in a special way. The/mediadirectory is used formount points. As we learned in thesecond lesson, the different physical storage devices (like hard disk drives) are attached to the file system tree in various places. This process of attaching a device to the tree is calledmounting. For a device to be available, it must first be mounted.

When your system boots, it reads a list of mounting instructions in the file/etc/fstab, which describes which device is mounted at which mount point in the directory tree. This takes care of the hard drives, but you may also have devices that are considered temporary, such as CD-ROMs and floppy disks. Since these are removable, they do not stay mounted all the time. The/mediadirectory is used by the automatic device mounting mechanisms found in modern desktop oriented Linux distributions. On systems that require manual mounting of removable devices, the/mntdirectory provides a convenient place for mounting these temporary devices. You will often see the directories/mnt/floppyand/mnt/cdrom. To see what devices and mount points are used, typemount.

Manipulating FilesThis lesson will introduce you to the following commands: cp- copy files and directories mv- move or rename files and directories rm- remove files and directories mkdir- create directoriesThese four commands are among the most frequently used Linux commands. They are the basic commands for manipulating both files and directories.Now, to be frank, some of the tasks performed by these commands are more easily done with a graphical file manager. With a file manager, you can drag and drop a file from one directory to another, cut and paste files, delete files, etc. So why use these old command line programs?The answer is power and flexibility. While it is easy to perform simple file manipulations with a graphical file manager, complicated tasks can be easier with the command line programs. For example, how would you copy all the HTML files from one directory to another, but only copy files that did not exist in the destination directory or were newer than the versions in the destination directory? Pretty hard with with a file manager. Pretty easy with the command line:[me@linuxbox me]$cp -u *.html destinationWildcardsBefore I begin with our commands, I want to talk about a shell feature that makes these commands so powerful. Since the shell uses filenames so much, it provides special characters to help you rapidly specify groups of filenames. These special characters are calledwildcards. Wildcards allow you to select filenames based on patterns of characters. The table below lists the wildcards and what they select:Summary of wildcards and their meanings

WildcardMeaning

*Matches any characters

?Matches any single character

[characters]Matches any character that is a member of the setcharacters. The set of characters may also be expressed as aPOSIX character classsuch as one of the following:Posix Character Classes

[:alnum:]Alphanumeric characters

[:alpha:]Alphabetic characters

[:digit:]Numerals

[:upper:]Uppercase alphabetic characters

[:lower:]Lowercase alphabetic characters

[!characters]Matches any character that is not a member of the setcharacters

Using wildcards, it is possible to construct very sophisticated selection criteria for filenames. Here are some examples of patterns and what they match:Examples of wildcard matching

PatternMatches

*All filenames

g*All filenames that begin with the character "g"

b*.txtAll filenames that begin with the character "b" and end with the characters ".txt"

Data???Any filename that begins with the characters "Data" followed by exactly 3 more characters

[abc]*Any filename that begins with "a" or "b" or "c" followed by any other characters

[[:upper:]]*Any filename that begins with an uppercase letter. This is an example of a character class.

BACKUP.[[:digit:]][[:digit:]]Another example of character classes. This pattern matches any filename that begins with the characters "BACKUP." followed by exactly two numerals.

*[![:lower:]]Any filename that does not end with a lowercase letter.

You can use wildcards with any command that accepts filename arguments.cpThecpprogram copies files and directories. In its simplest form, it copies a single file:[me@linuxbox me]$cpfile1 file2It can also be used to copy multiple files to a different directory:[me@linuxbox me]$cpfile1 file2 file3 directoryOther useful examples ofcpand its options include:Examples of the cp command

CommandResults

cpfile1file2Copies the contents offile1intofile2. Iffile2does not exist, it is created; otherwise,file2is overwritten with the contents offile1.

cp-ifile1file2Like above however, since the "-i" (interactive) option is specified, iffile2exists, the user is prompted before it is overwritten with the contents offile1.

cpfile1dir1Copy the contents offile1(into a file namedfile1) inside of directorydir1.

cp-Rdir1dir2Copy the contents of the directorydir1. If directorydir2does not exist, it is created. Otherwise, it creates a directory nameddir1within directorydir2.

mvThemvcommand performs two different functions depending on how it is used. It will either move one or more files to a different directory, or it will rename a file or directory. To rename a file, it is used like this:[me@linuxbox me]$mvfilename1 filename2To move files to a different directory:[me@linuxbox me]$mvfile1 file2 file3 directoryExamples ofmvand its options include:Examples of the mv command

CommandResults

mvfile1file2Iffile2does not exist, thenfile1is renamedfile2. Iffile2exists, its contents are replaced with the contents offile1.

mv-ifile1file2Like above however, since the "-i" (interactive) option is specified, iffile2exists, the user is prompted before it is overwritten with the contents offile1.

mvfile1file2file3dir1The filesfile1, file2, file3are moved to directorydir1.dir1must exist ormvwill exit with an error.

mvdir1dir2Ifdir2does not exist, thendir1is renameddir2. Ifdir2exists, the directorydir1is created within directorydir2.

rmThermcommand deletes (removes) files and directories.[me@linuxbox me]$rmfileIt can also be used to delete a directory:[me@linuxbox me]$rm -rdirectoryExamples ofrmand its options include:Examples of the rm command

CommandResults

rmfile1file2Deletefile1andfile2.

rm-ifile1file2Like above however, since the "-i" (interactive) option is specified, the user is prompted before each file is deleted.

rm-rdir1dir2Directoriesdir1anddir2are deleted along with all of their contents.

Be careful with rm!Linux does not have an undelete command. Once you delete a file withrm, it's gone. You can inflict terrific damage on your system withrmif you are not careful, particularly with wildcards.Before you usermwith wildcards, try this helpful trick: construct your command usinglsinstead. By doing this, you can see the effect of your wildcards before you delete files. After you have tested your command withls, recall the command with the up-arrow key and then substitutermforlsin the command.mkdirThemkdircommand is used to create directories. To use it, you simply type:[me@linuxbox me]$mkdirdirectory

I/O RedirectionIn this lesson, we will explore a powerful feature used by many command line programs calledinput/output redirection. As we have seen, many commands such aslsprint their output on the display. This does not have to be the case, however. By using some special notation we canredirectthe output of many commands to files, devices, and even to the input of other commands.Standard OutputMost command line programs that display their results do so by sending their results to a facility calledstandard output. By default, standard output directs its contents to the display. To redirect standard output to a file, the ">" character is used like this:[me@linuxbox me]$ls > file_list.txtIn this example, thelscommand is executed and the results are written in a file named file_list.txt. Since the output oflswas redirected to the file, no results appear on the display.Each time the command above is repeated, file_list.txt is overwritten (from the beginning) with the output of the commandls. If you want the new results to beappendedto the file instead, use ">>" like this:[me@linuxbox me]$ls >> file_list.txtWhen the results are appended, the new results are added to the end of the file, thus making the file longer each time the command is repeated. If the file does not exist when you attempt to append the redirected output, the file will be created.Standard InputMany commands can accept input from a facility calledstandard input. By default, standard input gets its contents from the keyboard, but like standard output, it can be redirected. To redirect standard input from a file instead of the keyboard, the "