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:
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:
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.
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:
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
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:
su linda
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.
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.
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.
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.
EXERCISE 3-2: VIRTUAL CONSOLES AND USER INFORMATION
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:
write 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:
linda@nuuk:~> write root
write: root is logged in more than once; writing to pts/1
hi root, I’m having a problem.
nuuk:~ #
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
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.
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.
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 protected]). 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.
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:
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).
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):
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.
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:
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:
nuuk:~ # pwd
/root
cd /usr/bin
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 /tmp/files
An important task from the command line is managing the files in the directories. Four important commands are used for this purpose:
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:
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:
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 rm command 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:
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.
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:
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
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).
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.
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:
wc filename
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.
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.
Summary
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:
In the next chapter, you’ll get some more details about working with the Linux file system.
3.135.201.52