Beginning the Linux Command Line, Second edition (2015)
CHAPTER 2. Performing Essential Command-Line tasks
At this point, you know the basics to get around. One very important topic that you’ve learned in Chapter 1 is how to get help. Now it’s time to expand your command-line skills by exploring some essential Linux commands. In this chapter, you’ll learn about the following topics:
· Changing your password
· Working with virtual consoles
· Becoming another user
· Obtaining information about other users
· Communicating with other users
· Exploring the Linux file system
· Working with files and directories
· Using some more Cool commands
Changing Your Password
As a user, you have a password that protects your account. This account includes all your personal settings and files, and therefore needs serious protection. Hence, it is a good idea to change your password regularly to minimize the risk that someone else gets to know your password and can use your credentials to authenticate. When changing a password, make sure it meets the following minimal requirements:
· A password should be long: at least six characters, though eight or more is better.
· Use complexity; mix letters, numbers, and other characters to make the password as difficult to guess as possible.
· Use upper- and lowercase letters.
· Make sure that your password doesn’t look like any word in the dictionary. Attackers use “dictionary attacks” in which they feed the entire contents of a dictionary to a brute-force password cracker, and if your password is in the dictionary, they will crack it.
Changing your password is not too hard—just use the passwd command to change your own password. Then, you first have to enter your old password. This is to prevent others from changing your password. Next, enter the new password twice. Also, make sure that your password meets the complexity rules; otherwise it will not be changed. In Listing 2-1, you can see what happens when changing your password.
Listing 2-1. Changing Your Password
Changing password for sander.
Reenter New Password:
If you are logged in as root, you can also change the password of other users. If you just want to change the password, that’s easy: type passwd followed by the name of the user whose password you need to change. It won’t ask you for the old password first. Since you are root, you should be able to modify users passwords without knowing the old password. There are also some options that you can use when changing a user’s password. Following are the most useful of these options:
· -d: Removes the password for the specified user account.
· -l: Locks an account. Useful if you know that the account is not to be used for a given period.
· -u: Unlocks an account that has been locked with -l.
· -e: Forces the user to change his or her password at the next login.
In Exercise 2-1 you’re going to change the password for a user. You’ll learn how to use passwd --stdin to do this without being prompted, which is convenient if you’d like to change passwords automatically by using a shell script.
EXERCISE 2-1: CHANGING PASSWORDS
1. Log in as root.
2. Type grep florence /etc/passwd. The command should show you a line starting with the text florence from /etc/passwd, which is the database of currently existing users.
3. Type echo secret | passwd --stdin florence. This will change the password for user florence to secret, without prompting you to enter it twice. In a following exercise you’ll test that this password modification has been successful.
Working with Virtual Consoles
On your Linux system, you work from a console. This is either a graphical or a text-based console. All distributions by default offer more than just this one console. They do this by using virtual consoles. You can consider a virtual console similar to the dumb terminal that was quite popular in the 1980s. This was a system where multiple screen/keyboard combinations were connected to one central computer that did all the work. Virtual consoles do more or less the same, they offer you more than one login environment, which is especially useful in a nongraphical environment. All virtual consoles are accessed from the same screen though.
Also for a modern Linux user, a virtual console can be very practical. Imagine a system administrator who wants to test a new setting and verify that it works for the user accounts. He or she can use one virtual console to change the setting as system administrator, while testing the setting by logging in as a normal user at another virtual console. Or imagine a developer tweaking the source code of a new program on one virtual console, while debugging the same program at another virtual console. Note that virtual consoles are particularly useful when working on a text-only environment. If your server shows a full graphical environment, you can just open a new terminal window instead.
Most Linux distributions offer six virtual consoles by default. The names of these consoles are tty1 through tty6. You can activate them using Ctrl+Alt+function key. So, to access virtual console number tty4, you need to press Ctrl+Alt+F4. If your system has started a graphical environment as well, you can use Ctrl+Alt+F7 or Ctrl-Alt-F1 to get back to the graphical environment. It is up to the descretion of the Linux distribution to decide which key sequence is used for switching back to the graphical environment.
Note In a nongraphical environment, you can skip the Ctrl key. So, to switch between tty1 and tty2, pressing Alt+F2 also works. In a graphical environment these keys typically are assigned to other functions.
You may notice that some distributions also use some of the higher-numbered virtual consoles (such as Ctrl+Alt+F10) for logging. Therefore, you should always at least check what happens at the higher- numbered virtual consoles. For instance, SUSE Linux writes kernel log messages to tty10, which can be useful when troubleshooting a problem.
Becoming Another User
There are basically two ways to authenticate to your Linux system: as the root or as a nonroot user. It is good habit not to use root by default. Since root can do anything, a small mistake may have big consequences. As root, you can accidentally destroy everything on your system, and Linux won’t ask whether you are sure about this action before wiping out everything on your hard drive (or whatever mistake you are about to make). Therefore, it is a good idea to log in as a normal user and get root permissions only when you really need them. To write a text document, you don’t need root permissions (unless it’s a configuration file). To change your IP address, however, you do need root permissions.
On Ubuntu, the root account by default cannot log in. Upon installation of Ubuntu, you will have created a user that is a member of the administrators group. All root tasks have to be executed by that user, and they start with sudo. So an Ubuntu user would type sudo passwd florence for instance, to reset the password of user florence.
To temporary change your identity, you can use the su (substitute user) command. (Ubuntu users: read the upcoming tip!) Its use is not hard; just issue su followed by the name of the user through whose identity you want to work. For instance:
would switch your current user account to the user account linda. If you are a normal user, you next have to enter a password. If you are root, this is not necessary (root is almighty, remember?). If you omit the name of the user you want to su to, the command assumes you want to become root. It will next prompt you to enter a password, which in this case is the password of the user root.
Tip If you’re on Ubuntu, you can’t use su just like that. Ubuntu uses the sudo mechanism instead, which is covered in Chapter 6 of this book. Here’s a quick-and-dirty method that helps you in using su, even on Ubuntu. It will enable you to execute privileged commands from now on. First, use the command sudo su. When asked for a password, enter the password assigned to your user account. Next, use the command passwd to give the user root a password. From this moment on, you can also log in as root on Ubuntu. If for security reasons you don’t like the fact that you can do so, read Chapter 6 for information on how to disable this feature. Until then, the goal is to help you work on the command line, and to do that, you will need root permissions from time to time.
When using su, it is a good idea to use the option - at all times. This option will give you a login shell instead of a subshell. That means that using the - as an option will ensure that the /etc/profile settings are applied. If you don’t use a -, this file is not processed, which might mess up your variables. If you don’t use the option -, you may still work with some settings that belong to the old user account. To prevent this, use su - at all times. This ensures that you work in the complete environment of the user you are switching to. In Listing 2-2, you can see what happens when a normal user uses su - to take the identity of user root.
Listing 2-2. Switching Identity with su -
sander@nuuk:~> su -
When done working as the other user, you can issue exit. This brings you back to your original user environment.
Tip! Linux admins typically work on a graphical desktop on top of Linux. To do their work, they would log in to the graphical desktop as a regular user, and open a root shell using the su - command. That makes them root in the terminal where they need to do their work, while still being a normal regular user in their default working environment.
Obtaining Information About Other Users
If you are using Linux on your personal computer at home, you are probably the only user who is logged in to it. However, if you are a Linux user at the Linux server in your company, there can be other users as well. In the latter case, it is good to know that several commands are available to help you in getting information about users who are currently connected to the same machine. To start, there is the users command. This command shows a short list of all users currently authenticated with no further details:
nuuk:~ # users
linda root root sander
If you want more information about the users who are logged in, who is a better option. By default, it shows you not only what users are logged in currently, but also where they are logged in from and at what time they logged in. Listing 2-3 shows the output of who when used without additional options.
Listing 2-3. who Gives More Detailed Information About What Users Are Doing
nuuk:~ # who
root tty1 Dec 10 09:11
sander pts/0 Dec 10 09:31 (192.168.139.1)
root pts/1 Dec 10 12:20 (192.168.139.1)
linda pts/2 Dec 10 12:21 (192.168.139.1)
The fact that who shows the IP address of remote users is particularly useful. If, for example, a user is misbehaving himself or herself, the administrator knows from which IP address that user is working, which makes it easier to take corrective measures.
If you want to see what a user is doing, the w command is helpful. This command shows you the names of users, where they are logged in from and at what time, current usage statistics, and what program they currently are using (or have used as the last program). Listing 2-4 gives an overview of w output.
Listing 2-4. Use w If You Want to See What a User Is Doing
nuuk:~ # w
13:17:23 up 4:31, 4 users, load average: 0.00, 0.00, 0.00
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
root tty1 09:11 4:05m 0.07s 0.07s -bash
sander pts/0 09:31 1:41m 0.13s 0.05s sshd: sander [priv]
root pts/1 12:20 0.00s 0.08s 0.00s w
linda pts/2 12:21 55:43 0.04s 0.04s -bash
If you want to get to know as much as possible about other users, try finger (notice that not all distributions install this tool by default). This command gives a summary of the current state of a user account. This includes a lot, including information about the amount of unread mail messages the user has! By default, finger works for local systems only. For a root user it is a useful command to find out about recent activity of users. Listing 2-5 shows an example of its output.
Listing 2-5. The finger command can be used to show more details about users
sander@nuuk:~> finger linda
Login: linda Name:
Directory: /home/linda Shell: /bin/bash
On since Wed Dec 10 12:21 (CET) on pts/2, idle 1:00, from 192.168.139.1
Mail last read Wed Dec 10 13:21 2015 (CET)
EXERCISE 3-2: VIRTUAL CONSOLES AND USER INFORMATION
1. Use the Ctrl+Alt+F2 key sequence to open a virtual console.
2. Log in a user florence, using the password “secret”.
3. Type w to see who else is currently logged in on this system.
4. Compare the output of this command with the output of the who command.
5. Type lastlog. Notice that even if you’re not the root user, you’ll see information about the last login time for all users on this system.
6. Still as florence, type finger root to get information about the root account. You’ll see why many administrators don’t like this command too much on their servers.
7. Type su - to open a root.
8. Type exit to close the root shell again.
Communicating with Other Users
From the Linux command line, you have some communication options as well. Some commands allow you to communicate in real time, providing chat functionality, while others are provided to allow you to send e-mail.
On Linux, there are two options to communicate with other users in real time. You can use write to talk to an individual user. If you want to send a message to all users, you can use wall. If you don’t want to receive messages from other users, use the mesg command to switch message reception off or on.
Individual Chat Sessions with write
If you want to chat in real time with another user on the system, you can use write. This command is provided for communication between two users. Its use is fairly simple: initiate a write session to another by using the write command followed by the name of the user you want to talk to. For instance, the following command would initiate a session from the current user to user linda:
Next, write opens a prompt after which the user can type text. This text is displayed line by line on the terminal of the other user. No matter what the user is doing, the text will be displayed, as long as the user has a terminal session that is open. If a user receives a write message from another user, he or she can reply to that by opening his or her own write session. As an illustration, the following procedure demonstrates how root and linda initiate and terminate a write session:
1. User linda opens the write session to root, using the command write root. This opens the write prompt, from which linda can type her text:
linda@nuuk:~> write root
write: root is logged in more than once; writing to pts/1
hi root, I’m having a problem.
2. At this moment, root receives linda’s message at his console. To reply, he has to press Enter to put away linda’s message first, and then enter the command write linda. Next, he can type his message, thereby establishing an active chat session with linda:
Message from linda@nuuk on pts/2 at 13:35 ...
hi root, I’m having a problem.
nuuk:~ # write linda
hi linda, how can I help you
We’ll, my mouse doesn’t react anymore
3. At the end of the session, both parties that are involved have to use the Ctrl+C key sequence to terminate the session. This will bring them back to their prompts, where they can continue their normal work.
Writing to all Users
Another tool for real-time communication is wall. This stands for write all, and you can probably guess that this tool is used to write a message to all users. It works in more or less the same way as write: after entering wall, the user who invokes wall writes a message, which is terminated by using the Ctrl+D key sequence. This message will show on the console of all users who are currently logged in. It needs no explanation that you should use this tool with care, as it is very annoying for users to receive wall messages frequently. In Listing 2-6, you can see an example of a wall session.
Listing 2-6. Writing a Message to All Users with wall
nuuk:~ # wall
I’ll shut down the system in 5 minutes
Broadcast Message from root@nuuk
(/dev/pts/1) at 15:27 ...
I’ll shut down the system in 5 minutes
With wall, you can also send the contents of a text file to other users. For instance, wall /tmp/mymessage.txt would send the contents of mymessage.txt to all users who are currently connected. This function is useful for a system administrator who wants to send a longer message to all users.
Disabling Real-Time Messages
If you don’t want to receive any messages from other users, use the mesg command. This command works with two arguments only. mesg n makes sure that no one can write messages to your console. If you want to open your console again for messages from other users, use mesg y.
Sending Mail from the Command Line
You may think that in order to send mail, you need a full-scale mail client, such as Thunderbird, Evolution, or Windows Mail. The Linux command line, however, also has a mail client, which you can invoke from the command line by using the mail command. I wouldn’t recommend replacing your normal mail client by mail, but if you want to send a message to an Internet or local user, or if you want to read system mail, the mail command offers an excellent solution to do that.
Note You can use the mail command to send mail to Internet users, but this requires DNS to be set up properly on your Linux machine and an SMTP process running. Notice that Ubuntu does not install smtp by default, if you want to use mail on Ubuntu, install it first using apt-get install dhcpclient.
To send a mail message to another user, you invoke the command as mail user, where user is the name of a local user (e.g., mail root) or a user on the Internet (e.g., mail email@example.com). Next, the mail program opens an interface where you first enter the subject, followed by the body of the mail message. When finished writing the mail body, you type a dot on a separate line and press Enter. This will tell the mail client that you’re done and offer the mail message to the SMTP process on your machine, which will take care of delivering it to the correct user. In Listing 2-7, you can see what happens when using the mail command from the command line.
Listing 2-7. Sending Messages with the mail Utility
nuuk:~ # mail linda
Subject: 4 PM meeting
Hi Linda, can we meet at 4 PM?
You can also run the mail utility completely from the command line, without it opening an interface that has you input text. This, for example, is very useful if you want shell scripts or scheduled jobs to send a message automatically if a certain error condition occurs. In these cases, the body of the mail message is not very important; you probably just want to deliver a mail message with a certain subject to the user. The next command shows you how to do this: it sends a message with the text “something is wrong” to the user root. Also, take notice of the < . construction. Normally, the mail command would expect a dot on a line on its own to indicate that the message is complete. By using input redirection with < ., the dot is provided on the command line.
mail -s "something is wrong" root < .
The mail command has some other useful options as well for sending mail:
· -a filename: Allows you to add a file as an attachment to your message.
· -c cc-addr: Specifies the name of a user you want to send a copy of the message to.
· -b bcc-addr: Sends a blind copy to a user. The recipient of the mail cannot see that you’ve sent a copy to this user also.
· -R reply-addr: Allows you to specify the reply address. A reply to this mail message is automatically sent to this reply address.
Apart from sending mail, you can read mail messages also with the mail utility. The utility, however, is meant to read system mail and is not a good choice to read your POP or IMAP mail from the mail server of your Internet provider. When invoking mail to read your system messages, you should just type mail. In reply, the mail client shows a list of mail messages that are waiting for you (see Listing 2-8).
Listing 2-8. Just Type mail to Display a List of All Mail Messages That Are Waiting for You
nuuk:~ # mail
mailx version nail 11.25 7/29/05. Type ? for help.
"/var/mail/root": 5 messages 5 unread
>U 1 firstname.lastname@example.orgSPI_AMP#160; Wed Nov 19 15:13 20/661 Meeting at 10 AM
U 2 email@example.comSPI_AMP#160; Fri Nov 21 09:48 20/661 10 AM meeting cancelled
U 3 firstname.lastname@example.orgSPI_AMP#160; Fri Dec 5 10:44 20/661 Nice day for Dutch users
U 4 email@example.comSPI_AMP#160; Fri Dec 5 12:28 19/568 hello
U 5 firstname.lastname@example.orgSPI_AMP#160; Wed Dec 10 08:48 20/661 Wanna go for coffee?
To read a message, just enter the message number, and you will see its text. When finished reading the message, press q to quit. After closing a message that you’ve read, you can type the reply command from within the mail interface to send a reply to the user who sent the message, or type delete, followed by the message number to delete the message from your system. Next, type quit to exit the mail interface.
Finding Your Way in the File System
Now that you know how to log in to your server, it is time to get more familiar with the way a Linux file system is organized with default files and directories. Even nowadays, it is still very important that you know your way around the file system; this is because Linux is still a file system–centric operating system. Even if you want to work only from the graphical environment, you must know where you can find all important files on your server. Knowing where to find files and directories will absolutely make working on the Linux command line easier.
All Linux distributions use more or less the same approach in organizing the directory structure on a system. This means that certain directories will always be present, no matter what distribution you are using. You may encounter small differences between distributions though. In this section, you’ll learn what default directories exist and what kinds of files you’ll find in these directories.
Tip! All the default directories are documented in man hier. Read this man page for a full and actual description of the default directories and their use.
On most Linux systems, you’ll find the following default directories (notice that minor differences may exist between distributions):
· /: The root directory is the starting point of your Linux file system. All other directories on your system exist in the root directory.
· /bin: This is the location where you find program files (binaries) accessible to all users. These are essential binaries that must be available at all times, even if there is a problem with other parts of your system. For that reason, the directory /bin is always on the root partition. In it you will find essential utilities and commands like /bin/bash (the shell), cp (used to copy files), and many more.
· /sbin: In this directory you will find binaries for the system administrator. These are critical binaries that must be available at all times in case you need to repair your system. In this directory, you will find commands and utilities you’d rather not see in the hands of your users, like the general system management tool yast2, or the partitioning tool fdisk.
· /boot: This directory contains everything you need to boot your server. One of the most important things that you’ll find in this directory is the kernel; this is the file with the name vmlinuz. (On some distributions, the version number is appended to the file name.) Other vital components are present as well, and the thing all of these have in common is that your server needs them to start.
· /dev: On a Linux system, all hardware you work with corresponds with a file on your system. If you want to address the hardware, you have to address the corresponding file. Notice that you’ll need root permissions to do so though. You can find all these device files in the directory /dev. You will find, for example, a device called /dev/cdrom that refers to the optical drive that might be present in your system. Other important device files are /dev/sda, which typically refers to your hard disk, or /dev/null, which you can use to redirect error messages to.
· /etc: Most services running on Linux use an ASCII text file to store all necessary configuration. These text files are kept in the directory /etc. In this directory, you will find some important configuration files like /etc/passwd, which contains the database of local Linux users.
· /home: The personal files of a user are stored in his or her home directory, no matter if you are working on a Linux server or a personal desktop. The directory /home is used to store each user’s home directory. When installing a Linux system, it may be wise to put this directory on a partition on its own to separate user data files from operating system components. That minimizes the risk that you’ll lose all your personal files if something happens to the installation of your operating system.
· /lib: Many programs that are used in a Linux environment share some of their code. This shared code is stored in different library files. All the libraries needed by binaries that are in a subdirectory of your file system root are in the directory /lib. You will also find some other important modules in this directory, like the driver modules that are used by the kernel of your server. For 64 bits library files, a directory with the name /lib64 exists.
· /media: On a Linux system, to access files that are not on the hard disk of your computer, you need to make the medium accessible. You do this by mounting it (mounting devices is explained in more detail in Chapter 3). When you mount a CD-ROM, for example, you connect it to a directory on your file system. This must be a directory that exists before you start mounting anything. The default directory that is used for regular mounts on most distributions is /media. In this directory, a subdirectory is created automatically when a new removable device is detected. CDs as well as USB sticks will appear here (and on the graphical desktop as well) once they are mounted with the label of the device used as the name of the directory where the device is mounted.
· /mnt: On older Linux systems, /mnt was the default directory for mounting devices. On more recent systems, this has been replaced by the /media directory. However, /mnt still has a purpose: it is used for mounts that don’t occur very often and which are created manually, such as a mount to a server that has to be accessed only once. The /mnt directory is ideal for testing purposes.
· /usr: This directory is probably the largest directory on your system. Here you can find almost all user-accessible files. Some people like to compare it to the Program Files directory on a Windows system. Because there are so many files in this directory, inside it you will find an entire structure of subdirectories, including /usr/bin, in which most programs are stored and /usr/src, where you can put the source files of the open source programs and kernel you use. Because there are so many files in the /usr directory, it is quite usual to put it on its own partition.
Tip Have you always wanted to find out how much space a directory occupies on your hard disk? Use du –hs from a console environment. It will show you the disk usage of a specified directory. The normal output of this command is in blocks; the parameter –h presents the output in a human-readable form. The option -s makes sure that you see the summary for the selected directory only, and not how much disk space every individual file uses. For example, use du –hs /usr to find out exactly how much space is occupied by /usr. In Listing 2-9, you can see the result of the du -h /usr command.
Listing 2-9. Use du -hs to Find Out How Much Disk Space a Directory and Its Contents Occupy
nuuk:/ # du -hs /usr
· /opt: In /usr you will find a lot of binaries. Many of these are small software packages. Normally, large software installations, such as office suites and other large programs, are stored in /opt. For example, the Gnome graphical interface, the OpenOffice suite, or the Oracle database (if installed) could be subdirectories of this directory. There seems to be no good concensus about the use of this directory, so you may find some of these packages in /usr as well.
· /proc: This is a strange directory, because it doesn’t really exist on the hard disk of your computer. /proc is an interface to the memory of your computer. An advanced administrator can use it to tune the workings of the computer and get information about its current status. You can find a lot of information about your computer in the files in this directory. For example, try the command cat /proc/cpuinfo to show the contents of the text file /proc/cpuinfo (you must be root to do this). This command will show you a lot of information about the processor(s) in your computer, as you can see in Listing 2-10.
Listing 2-10. Use cat /proc/cpuinfo to Get Information About Features Your Computer’s CPU Is Using
nuuk:/ # cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 15
model name : Intel(R) Core(TM)2 Duo CPU T7500 @ 2.20GHz
stepping : 8
cpu MHz : 2201.481
cache size : 4096 KB
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 10
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss nx
constant_tsc pni ds_cpl ida
bogomips : 4417.91
· /root: Ordinary users have their home directories in /home. A system administrator is not a normal user; in a UNIX environment, the system administrator is therefore respectfully called “superuser.” Since this user may have some important tools in his or her home directory, this directory is not in /home with those of the other users. Instead, the user root uses /root as his or her home directory. There is a good reason for this: on many servers the directory /home is on a separate partition. If for any reason you cannot access this partition anymore, user root at least still has access to his or her home directory, in which he or she has probably stored some important files.
· /run: This directory is used for run-time configuration. Within this directory, separate subdirectories can be created for different users and processes and each of these can create files in these subdirectories. Files in /run are typically removed automatically when they are no longer needed.
· /srv: On some distributions, you will find all files from some important services in this directory. For example, it is used to store your entire web server and FTP server file structures on SUSE Linux. Some distributions, such as Red Hat and derivatives, don’t use /srvbut store this type of information in /var.
· /sys: This directory can be used to store information about the state of your system. Its use is like the use of /proc, with the difference that the information in /sys is kept on the hard disk of your server, so it is still available after you have rebooted it. The information in /sys is more directly related to the hardware you are using on your server, whereas /proc is used to store information about the current state of the kernel.
· /tmp: As the name suggests, /tmp is used for temporary files. This is the only directory on the entire system where every user can write to. This is, however, a bad idea, because the content of this directory can be wiped out automatically by any process or user without any warning being issued before that happens. It is common to use a RAM file system for the /tmp directory, to make sure it is fast and cleaned automatically upon reboot.
· /var: This last directory you will find on any Linux computer. This directory contains mostly files that are created by your system whose content can grow very fast. For example, think of spooling of print jobs—these are found in this directory. Also very common is /var/log, the directory that is used by rsyslog to write log files about events that have occurred on a Linux computer.
Working with the Linux File System
On a Linux system, everything is treated as a file. Even a device like your hard disk is addressed by pointing to a file (which, for your information, has the name /dev/sda in most cases). Therefore, to handle Linux well, it is important that you can find your way in the Linux file system. In this section, you’ll learn the basics of working with the file system (more details are in Chapter 3). The following subjects are covered:
· Working with directories
· Working with files
Working with Directories
On Linux, directories are used as is the case with folders on Windows. Because files are normally organized in directories, it is important that you know how to handle them. This involves a few commands:
· pwd: Use this to show your current directory. It will display the complete directory path reference, which always starts at the root directory:
nuuk:~ # pwd
· cd: Once you know what your current directory is, you can change to another directory using the cd command. When using cd, you should be aware of some features in the Linux file system:
· Linux file and directory names are case sensitive. Hence, bin and BIN are not the same!
· If you want to go to a directory that is directly under the root directory, make sure to put a / in front of the directory name. Without the slash, this command will try to find the directory as a subdirectory in the current directory.
· The cd command has one argument only: the name of the directory you want to go to. For instance, the following command brings you to the directory /usr/bin, which is directly under the root directory of the file system:
Tip Switching between directories? Use cd - to return to the last directory you were in. Also good to know: if you just type cd, the cd command brings you to your home directory.
· mkdir: If you need to create a new directory, use mkdir. For instance, the following would create a directory named files in the directory /tmp:
· With mkdir you can create a complete directory structure in one command as well, which is something you can’t do on other operating systems. For example, the command mkdir /some/directory will fail if /some does not already exist. In that case, you can force mkdir to create /some as well: do this by using the mkdir -p /some/directory command.
· rmdir: The rmdir command is used to remove directories. However, this isn’t the most useful command, because it works only on directories that are already empty. If the directory still has files and/or subdirectories in it, use rm –r, or better, rm –rf, which makes sure that you’ll never get a prompt for confirmation. It’s best to be sure what you’re doing when using this option
Working with Files
An important task from the command line is managing the files in the directories. Four important commands are used for this purpose:
· ls lists files.
· rm removes files.
· cp copies files.
· mv moves files.
Listing Files with ls
The generic syntax of ls is not too hard:
ls [options] filename
For instance, the following would show all files in the directory /usr, displaying their properties as well:
ls -l /usr
See Listing 2-11 for an example. In this example you can see that different columns are used to show the attributes of the files:
· File type: The very first letter shows the file type. If a - is displayed, it is a regular file. In this example, you can see one file that has the d type. This is not a regular file, but a directory.
· Permissions: Directly after the file type, you can see the permissions assigned to the file. There are nine positions that show you the file permissions. In Chapter 7, you’ll learn much more about them.
· Ownership: On Linux, every file has a user owner and a group owner. In the following example, they are set to user root and group root for all files.
· File size: Next to the group owner, the size of the file is displayed.
· Creation date and time: For every file, creation date and time are shown as well.
· File name: In the last column of ls -l output, you can see the name of the file.
Listing 2-11. Example Output of ls -l
root@RNA:/boot# ls -l
-rw-r--r-- 1 root root 414210 2007-04-15 02:19 abi-2.6.20-15-server
-rw-r--r-- 1 root root 83298 2007-04-15 00:33 config-2.6.20-15-server
drwxr-xr-x 2 root root 4096 2007-07-29 02:51 grub
-rw-r--r-- 1 root root 6805645 2007-06-05 04:15 initrd.img-2.6.20-15-server
-rw-r--r-- 1 root root 94600 2006-10-20 05:44 memtest86+.bin
-rw-r--r-- 1 root root 812139 2007-04-15 02:20 System.map-2.6.20-15-server
-rw-r--r-- 1 root root 1763308 2007-04-15 02:19 vmlinuz-2.6.20-15-server
-rw-r--r-- 1 root root 240567 2007-03-24 10:03 xen-3.0-i386.gz
Apart from the option -l, ls has many other options as well. An especially useful one is the -d option, and the following example shows why. When working with the ls command, wildcards can be used. So, ls * will show a list of all files in the current directory, ls /etc/*a.*will show a list of all files in the directory /etc that have an “a” followed by a dot somewhere in the file name, and ls [abc]* will show a list of all files whose names start with either an “a,” “b,” or “c” in the current directory. But something strange happens without the option -d. If a directory matches the wildcard pattern, the entire contents of that directory are displayed as well. This doesn’t really have any useful application, so you should always use the -d option with ls when using wildcards. Some of the most useful options that you can use with ls are listed here:
· -a: Also show files whose name starts with a dot. Normal users will not see these by default, as files whose names start with a dot are hidden files.
· -l: Provide a long listing. This shows properties of files as well, not just file names.
· -d: Shows the names of directories and not their contents.
· -R: Shows the contents of subdirectories as well.
· -t: Sort files by access time.
· -h: Indicates human readable. This mentions file sizes in kilobytes, megabytes, or gigabytes, instead of just bytes, which is the default setting. Use this option with the -l option only.
· -S: Sorts files by file size. This option is useful only when used together with the option -l.
Note A hidden file is a file whose name starts with a period. Most configuration files that are stored in user home directories are created as hidden files to prevent the user from deleting the file by accident.
Removing Files with rm
Cleaning up the file system is another task that needs to be performed regularly, and for this you’ll use the rm command. For example, rm /tmp/somefile removes somefile from the /tmp directory. If you are root or if you have all the proper permissions on the file, you will succeed without any problem. (See Chapter 7 for more on permissions.) Removing files can be a delicate operation (imagine removing the wrong files), so it may be necessary to push the rm command a little to convince it that it really has to remove everything. You can do this by using the -f (force) switch (but only if you really are quite sure you want to do so). For example, use rm -f somefile if the command complains that somefile cannot be removed for some reason. Conversely, to stay on the safe side, you can also use the -i option to rm, which makes the command interactive. When using this option, rm will ask for every file that it is about to remove if you really want to remove it.
The rm command can be used to wipe entire directory structures as well; in this case the -r option has to be used. If this option is combined with the -f option, the command will become very powerful and even dangerous. For example, use rm -rf /somedir to clear out the entire content of /somedir, including the directory /somedir itself.
Obviously, you should be very careful when using rm this way, especially because a small typing mistake can have serious consequences. Imagine, for example, that you type rm -rf / somedir (with a space between / and somedir) instead of rm -rf /somedir. The rmcommand will first remove everything in the root of the file system, represented by the directory / and, when it is finished with that, it will remove somedir as well. Hopefully, you understand that the second part of the command is no longer required once the first part of the command has completed.
The rm command also has some useful options:
· -r: Recursive, removes files from all subdirectories as well
· -f: Force, doesn’t ask anything, just removes what the user asks to remove
· -i: Interactive, asks before removing a file
· -v: Verbose, shows what is happening
In Listing 2-12, you can see what happens when removing the contents of a directory with all its subdirectories with the options -ivR. As you can see, it is not a very practical way of removing all files, but at least you’ll be sure not to remove anything by accident.
Listing 2-12. Removing Files with rm -ivR *
nuuk:/test # rm -ivR *
rm: descend into directory `etc'? y
rm: remove regular file `etc/fstab'? y
rm: descend into directory `etc/udev'? y
rm: descend into directory `etc/udev/rules.d'? y
rm: remove regular file `etc/udev/rules.d/65-cdrom.rules'? y
rm: remove regular file `etc/udev/rules.d/31-network.rules'? y
rm: remove regular file `etc/udev/rules.d/56-idedma.rules'?
Caution Be very careful using potentially destructive commands like rm. There is no good undelete mechanism for the Linux command line, and, if you ask Linux to do something, it doesn’t ask whether you to confirm (unless you use the -i option).
Copying Files with cp
If you need to copy files from one location in the file system to another, use the cp command. This command is straightforward and easy to use; the basic structure of this command is as follows:
cp source destination
As source, you typically specify the name of a directory, files, or a file pattern (like * to refer to all files). For example, use cp ~/* /tmp to copy all files from your home directory to the /tmp directory. As you can see, in this example I introduced a new item: the tilde (~). The shell interprets this symbol as a way to refer to the current user’s home directory (normally /home/username for ordinary users and /root for the user root). If subdirectories and their contents need to be included in the cp command as well, use the option -r.
The cp command has some useful options, some of which are listed here:
· -a: Archive; use this option to make sure that all properties of the files you copy are copied as well. Use this if you want to make sure that permissions and other file properties are copied correctly.
· -b: Backup; if your cp command will overwrite an existing destination file, this option makes sure that a backup is created of this destination file first.
· -f: Force; if a file at the destination prohibits you from copying your file, this option will force the copy. This means that the destination file is overwritten and cp tries again.
· -i: Interactive; when using this option, cp asks before overwriting an existing file at the destination location.
· -p: Preserve; when using this option, cp makes sure that attributes of the file, such as owners and permissions, are copied as well.
· -r: Recursive; this option makes sure that directories are copied recursively.
· -u: Update; this very useful option only copies if the destination file is older than the source file, or if the destination file does not exist.
You should be aware that by default the cp command does not copy hidden files. It just copies regular files. To copy hidden files, you need to refer to the hidden files specifically. The command cp .* ~ for instance would copy all hidden files, as the first argument refers to all files that have a name starting with a dot. In exercise 2.3 you’ll also learn a convenient way to copy hidden files.
Moving Files with mv
Sometimes you need to copy your files, at other times you need to move them to a new location. This means that the file is removed from its source location and placed in the target location. The syntax of the mv command that you use for this purpose is comparable to the syntax of cp:
mv source destination
For example, use mv ~/somefile /tmp/otherfile to move the somefile file to /tmp. If a subdirectory with the name otherfile already exists in the /tmp directory, somefile will be created in this subdirectory. If /tmp has no directory with this name, the command will save the contents of the original somefile under its new name otherfile in the /tmp directory.
The mv command also does more than just move files. You can use it to rename files, as well as directories, regardless of whether there are any files in those directories. If, for example, you need to rename the directory /somedir to /somethingelse, use mv /somedir /somethingelse.
EXERCISE 2-3: WORKING WITH FILES
1. Open a root shell.
2. Type mkdir /data/files. It will give you an error message, as the /data directory doesn’t exist yet.
3. To create the entire path that is specified as an argument to mkdir, use mkdir -p /data/files. This will create the directory /data as well as its subdirectory /files.
4. Type pwd. This shows your current directory, which should be /root.
5. Type ls and compare its output to ls -a. The latter command also shows all hidden files.
6. Type cp /root /data/files.
7. Use ls -al /data/files/*. (don’t include the dot in your command) You’ll see that nothing has been copied.
8. Use cp -R /root /data/files and check the contents of /data/files again. You’ll see that only files that are not hidden files have been copied.
9. Remove the contents of /data/files, using rm -f /data/files/*
10.Type cp -R /root/. /data/files and check the contents of /data/files again. You’ll now see that also the hidden files have been copied.
Some commands don’t really fit into a certain theme, but are just cool and useful. In this final section, you’ll learn about these commands. I’ll give a short description of the following commands:
Displaying a Calendar with cal
Want to know if Christmas 2018 is in a weekend? Linux has a cool utility to help you with that: cal. If you just type cal, this utility will show you the calendar of the current month. You can, however, also include a year or a month and a year as its arguments to display the calendar for a given month or a specific year. For example, the command cal 12 2018 shows you the calendar for December 2018 (see Listing 2-13).
Listing 2-13. With cal You Can Show the Calendar for a Specific Month or Year
nuuk:/test # cal 12 2018
Su Mo Tu We Th Fr Sa
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
Clearing Your Screen with clear
Want to clear your screen so that you can see in a better way what you are doing? Use clear to do that. This command takes no argument—just typing clear will do the job. You may also prefer to use the key sequence Ctrl+L, which does exactly the same.
Displaying System Information with uname and hostname
In some cases you need to know more about your system. For this purpose, you can use the uname command. When using it without any arguments, it will just show you what kind of kernel you are using. This will normally be a Linux kernel, and that information might not be too useful as you probably already were aware of using Linux. However, you can also use uname to display what kernel version you are using (uname -r), or what type of CPU you are using (uname -p). And if you just want to see all there is to show about your computer, use uname -a. An example of this command is shown in Listing 2-14.
Listing 2-14. Showing System Information with uname -a
[root@server1 files]# uname -a
Linux server1.example.com 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
You may have noticed that uname shows a lot of information, but it doesn’t tell you what the name of your computer is. For this purpose, better use the hostname command. If you use it without arguments, it just shows the short host name, which is probably the same as what you already see at your computer’s shell prompt. If you also want to see the name of the DNS domain that your computer is in, use hostname -f.
Counting Words, Lines, and Characters with wc
In some situations, it is useful to know how many words there are in a file. For this purpose, Linux has the wc (wordcount) command. It will not only show you words, but also characters and lines that are in the target file. Its use is easy:
The result looks like what you see in Listing 2-15. It first shows you lines, followed by the number of words and the number of characters in the file. The wc command is also useful in a pipe. Some Linux commands generate a lot of output. Before starting to scroll up, you might want to check how much output really is produced. You can find out by piping the output of the command to wc, and you’ll see exactly how many lines, words and characters this command has produced.
Listing 2-15. Counting Lines, Words, and Characters in a File with wc
nuuk:/ # wc /etc/hosts
23 77 683 /etc/hosts
Changing and Showing Date and Time with date
At the end of the working day, you probably want to know when it is time to go home. The date command helps you with this. When used without arguments, this command shows you the current date and time, but you can also use arguments to change the time or date. For instance, date -s 14:48 sets the time to 2:48 p.m. You can also work with an mmddhhmm argument to change month, date, hour, and minute. For instance, the command date 12111449 sets the current date and time to 2:49 on December 11.
In this chapter, you’ve acquired some important basic skills to work with Linux on the command line. You have first learned all there is to know about your session on the Linux computer. This includes logging in and out, working with virtual consoles, and working as another user. Next, you’ve learned how to work together with other users. You’ve read how you can find out which users are connected to the system and how you can communicate with those users. Following that, you’ve read how to work with files and directories. Finally, at the end of this chapter, you’ve learned about some other useful commands. The following commands were covered in this chapter:
· passwd: Change passwords.
· su: Become another user.
· users: See who is connected.
· who: See who is connected.
· w: See who is connected.
· finger: Get information about a user.
· write: Send a real-time message to one user.
· wall: Send a real-time message to all users.
· mesg: Disable or enable reception of real-time messages.
· mail: Send e-mail to other users.
· du: See how much disk space a directory occupies.
· cat: Show contents of a text file.
· pwd: Print working directory.
· cd: Change to another directory.
· mkdir: Make a directory.
· rmdir: Remove a directory.
· ls: List files.
· rm: Remove files.
· cp: Copy files.
· mv: Move files.
· cal: Show a calendar.
· clear: Clear screen.
· uname: Show system information.
· wc: Count words, lines, and characters in a text file.
· date: Show and change current date and time.
In the next chapter, you’ll get some more details about working with the Linux file system.