Linux bible

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Background commands

Some commands can take a while to complete. Sometimes, you may not want to tie up your shell waiting for a command to fi nish. In those cases, you can have the commands run in the background by using the ampersand (&). Text formatting commands (such as nroff and troff, described earlier) are examples of commands that are often run in the background to format a large document. The following is an example of a command being run in the background: $ troff -me verylargedocument | lpr & Don't close the shell until the process is completed, or that kills the process. Other ways to manage background and foreground processes are described in Chapter 6, "Managing Running Processes."

How to diable the history feature?

Some people disable the history feature for the root user by setting the HISTFILE to /dev/null or simply leav-ing HISTSIZE blank. This prevents information about the root user's activities from potentially being exploited. If you are an administrative user with root privileges, you may want to consider emptying your fi le upon exiting as well for the same reasons. Also, because shell history is stored permanently when the shell exits properly, you can prevent storing a shell's history by killing a shell. For example, to kill a shell with process ID 1234, type kill -9 1234from any shell.

What is the command to show date with other formats?

The date command has some special types of options. By itself, date simply prints the current day, date, and time as shown above. But the date command supports a special + format option, which lets you display the date in different formats. Type date --help to see different format indicators you can use. $ date Tue Oct 21 09:08:38 EST 2014 $ date +'%d/%m/%y' 10/21/14 $ date +'%A, %B %d, %Y' Tuesday, October 21, 2014

Using the shell prompt 1

The default prompt for a regular user is simply a dollar sign: $ The default prompt for the root user is a pound sign (also called a hash mark): #

What's the command to show files and directories?

The ls command lists the files and directories in your current directory $ ls Desktop Downloads Pictures Templates Documents Music Public Videos

What's the command to show files and directories and hidden files?

The ls command, by itself, shows all regular fi les and directories in the current directory. By adding the -a, you can also see the hidden fi les in the directory (those beginning with a dot). $ ls Desktop Documents Downloads Music Pictures Public Templates Videos $ ls -a Desktop .gnome2_private .lesshst Public .. Documents .gnote .local Templates .bash_history Downloads .gnupg .mozilla Videos .bash_logout .emacs .gstreamer-0.10 Music .xsession-errors .bash_profile .esd_auth .gtk-bookmarks Pictures .zshrc .bashrc .fsync.log .gvfs Pictures

How the directories are checked in the PATH?

The path directory order is important. Directories are checked from left to right. So, in this example, if there is a command called foo located in both the /bin and /usr/bin directories, the one in /bin is executed. To have the other foo command run, you either type the full path to the command or change your PATH variable. (Changing your PATH and adding directories to it are described later in this chapter.)

Piping between commands 1

The pipe (|) metacharacter connects the output from one command to the input of another command. Example: $ cat /etc/passwd | sort | less This command lists the contents of the /etc/passwd fi le and pipes the output to the sort command. The sort command takes the usernames that begin each line of the /etc/passwd fi le, sorts them alphabetically, and pipes the output to the less command (to page through the output)

What's the command to show the current directory?

The pwd command shows your current working directory. $ pwd /home/chris

How to display the command history?

The shell history is a list of the commands that you have entered before. Using the history command in a bash shell, you can view your previous commands

Expanding arithmetic expressions

Sometimes, you want to pass arithmetic results to a command. There are two forms you can use to expand an arithmetic expression and pass it to the shell: $[expression] or $(expression). The following is an example: $ echo "I am $[2015 - 1957] years old." I am 58 years old. The shell interprets the arithmetic expression fi rst (2015 - 1957) and then passes that information to the echo command. The echo command displays the text, with the results of the arithmetic (58) inserted. Here's an example of the other form: $ echo "There are $(ls | wc -w) files in this directory. "There are 14 files in this directory. This lists the contents of the current directory (ls) and runs the word count command to count the number of files found (wc -w). The resulting number (14, in this case) is echoed back with the rest of the sentence shown

How to locate the command if are not in PATH variable?

If a command is not in your PATH variable, you can use the locate command to try to find it. Using locate, you can search any part of the system that is accessible to you (some fi les are only accessible to the root user). For example, if you wanted to fi nd the location of the chage command, you could type the following: $ locate chage /usr/bin/chage/usr/sbin/lchage /usr/share/man/fr/man1/chage.1.gz /usr/share/man/it/man1/chage.1.gz /usr/share/man/ja/man1/chage.1.gz /usr/share/man/man1/chage.1.gz /usr/share/man/man1/lchage.1.gz /usr/share/man/pl/man1/chage.1.gz /usr/share/man/ru/man1/chage.1.gz /usr/share/man/sv/man1/chage.1.gz /usr/share/man/tr/man1/chage.1.gz1! Notice that locate not only found the chage command, but also found the lchage command and a variety of man pages associated with chage for different languages. The locate command looks all over your filesystem, not just in directories that contain commands.

Where is the command date in the path?

If you know the directory that contains the command you want to run, one way to run it is to type the full, or absolute, path to that command. For example, you run the date com-mand from the /bin directory by typing $ /bin/date

Keystrokes for Navigating Command Lines

If you type something wrong on a command line, the bash shell ensures that you don't have to delete the entire line and start over. Likewise, you can recall a previous command line and change the elements to make a new command. To do the editing, you can use a combination of control keys, meta keys, and arrow keys.

How to show the where is the command echo?

The better way is to have commands stored in well-known directories and then add those directories to your shell's PATH environment variable. The path consists of a list of directories that are checked sequentially for the commands you enter. To see your current path, type the following: $ echo $PATH/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:↵/home/chris/bin

How to add your own command?

If you want to add your own commands or shell scripts, place them in the bin directory in your home directory (such as /home/chris/bin for the user named chris). This directory is automatically added to your path in some Linux systems, although you may need to create that directory or add it to your PATH on other Linux systems. So, as long as you add the command to your bin with execute permission, you can begin using it by simply typing the com-mand name at your shell prompt. To make commands available to all users, add them to /usr/local/bin. Unlike some other operating systems, Linux does not, by default, check the current direc-tory for an executable before searching the path. It immediately begins searching the path, and executables in the current directory are run only if they are in the PATH variable or you give their absolute (such as /home/chris/scriptx.sh) or relative (for example, ./scriptx.sh) address.

Using the shell prompt 2

In most Linux systems, the $ and # prompts are preceded by your username, system name, and current directory name. For example, a login prompt for the user named jake on a computer named pine with /usr/share/ as the current working directory would appear as [jake@pine share]$

What's the command to show files and directories ?

In the previous example, the --hide option tells the ls command to not display the file or directory named Desktop when listing the contents of the directory. $ ls --hide=Desktop Documents Music Public Videos Downloads Pictures Templates

Piping between commands 2

$ gunzip < /usr/share/man/man1/grep.1.gz | nroff -c -man | less In this example, the contents of the grep man page (grep.1.gz) are directed to the gunzip command to be unzipped. The output from gunzip is piped to the nroff com-mand to format the man page using the manual macro (-man). The output is piped to the less command to display the output. Because the fi le being displayed is in plain text, you could have substituted any number of options to work with the text before displaying it. You could sort the contents, change or delete some of the content, or bring in text from other documents. The key is that, instead of all those features being in one program, you get results from piping and redirecting input and output between multiple commands.

How to compress a directory or subdirectory?

$ tar -cvf backup.tar /home/chris In the tar example just shown, the options say to create (c) a file (f) named backup.tar that includes all the contents of the /home/chris directory and its subdirectories and show verbose messages as the backup is created (v). Because backup.tar is an argument to the f option, backup.tar must immediately follow the option.

Another way to work with the history(with the text editor vi)

Another way to work with your history list is to use the fc command. Type fc followed by a history line number, and that command line is opened in a text editor (vi by default; type :wq to save and exit or :q! to just exit if you are stuck in vi). Make the changes that you want. When you exit the editor, the command runs. You can also give a range of line numbers (for example, fc 100 105). All the commands open in your text editor, and then run one after the other when you exit the editor.After you close your shell, the history list is stored in the .bash_history fi le in your home directory. Up to 1,000 history commands are stored for you by default

Using virtual consoles

Ctrl+Alt+F1 (or F2, F3, F4, and so on up to F6 on most Linux systems) to display one of seven virtual consoles. You should see a plain-text login prompt. Log in using your username and password. Try a few commands. When you are fi nished, type exit to exit the shell. Then press Ctrl+Alt+F1 to return to your graphical desktop interface.

Where is the common default path for a regular Linux use?

Directories in the path list are separated by colons. Most user commands that come with Linux are stored in the /bin, /usr/bin, or /usr/local/bin directories. The /sbin and /usr/sbin directories contain administrative commands (some Linux systems don't put those directories in regu-lar users' paths). The last directory shown is the bin directory in the user's home directory (/home/chris/bin)

How to find where is the command located?

For example, to find out where the bash shell command is located, type the following: $ type bash bash is /bin/bash

Using Shell Variables 2

For example: $ echo $USERchris This command prints the value of the USER variable, which holds your username (chris). Substitute any other value for USER to print its value instead. When you start a shell (by logging in via a virtual console or opening a Terminal window), many environment variables are already set. Table 3.5 shows some variables that either are set when you use a bash shell or can be set by you to use with different features.

Example of Command-line completion

Here are a few examples of command completion. (When you see <Tab>, it means to press the Tab key on your keyboard: $ echo $OS<Tab> $ cd ~ro<Tab> $ fing<Tab> The fi rst example causes $OS to expand to the $OSTYPE variable. In the next example, ~ro expands to the root user's home directory (~root/). Next, fing expands to the finger command The following shows the result you would get if you checked for possible completions on$P: $ echo $P<Tab><Tab> $PATH $PPID $PS1 $PS2 $PS4 $PWD$ echo $P In this case, there are six possible variables that begin with $P. After possibilities are displayed, the original command line returns, ready for you to complete it as you choose.

How the shell checks the type of command?

Here is the order in which the shell checks for the commands you type: 1.Aliases. Names set by the alias command that represent a particular command and a set of options. Type alias to see what aliases are set. Often, aliases enable you to define a short name for a long, complicated command. (I describe how to create your own aliases later in this chapter.) 2.Shell reserved word. Words reserved by the shell for special use. Many of these are words that you would use in programming-type functions, such as do, while, case, and else. (I cover some of these reserved words in Chapter 7, "Writing Simple Shell Scripts.") 3.Function. This is a set of commands that are executed together within the current shell. 4.Built-in command. This is a command built into the shell. As a result, there is no representation of the command in the fi lesystem. Some of the most com-mon commands you will use are shell built-in commands, such as cd (to change directories), echo (to output text to the screen), exit (to exit from a shell), fg(to bring a command running in the background to the foreground), history(to see a list of commands that were previously run), pwd (to list the present working directory), set (to set shell options), and type (to show the location of a command). 5.Filesystem command. This command is stored in and executed from the computer's fi lesystem. (These are the commands that are indicated by the value of the PATHvariable.)

Connecting and Expanding Commands

Metacharacters include the pipe character (|), ampersand (&), semicolon (;), right paren-thesis ( ) ), left parenthesis ( ( ), less than sign (<), and greater than sign (>). The next sections describe how to use metacharacters on the command line to change how com-mands behave

All the command are in the PATH variable?

Not all the commands you run are located in directories in your PATH variable. Some com-mands are built into the shell. Other commands can be overridden by creating aliases that defi ne any commands and options that you want the command to run. There are also ways of defi ning a function that consists of a stored series of commands.

How to remove an alias?

While you are in the shell, you can check which aliases are set by typing the alias com-mand. If you want to remove an alias, type unalias. (Remember that if the alias is set in a confi guration fi le, it will be set again when you open another shell.)

Sequential commands

You can do this by typing several commands on the same command line and separating them with semicolons (;): $ date ; troff -me verylargedocument | lpr ; date The fi rst command (date) showed the date and time before the formatting started. The troff command formatted the document and then piped the output to the printer. When the formatting was fi nished, the date and time were printed again (so I knew how long the troff command took to complete) Another useful command to add to the end of a long command line is mail. You could add the following to the end of a command line. ; mail -s "Finished the long command" [email protected] Then, for example, a mail message is sent to the user you choose after the command completes.

How to show information about the login session?

You can see information about your current login session $ who -uH NAME LINE TIME IDLE PID COMMENT chris tty1 Jan 13 20:57 . 2013 The output from this who command shows that the user chris is logged in on tty1 (which is the fi rst virtual console on the monitor connected to the computer), and his login session began at 20:57 on January 13. The IDLE time shows how long the shell has been open without any command being typed (the dot indicates that it is currently active). PID shows the process ID of the user's login shell. COMMENT would show the name of the remote computer the user had logged in from, if that user had logged in from another computer on the network, or the name of the local X display if that user were using a Terminal window (such as :0.0).

Help command

You can use the --help option with most commands to see the options and arguments that they support: for example, try typing hostname --help. example ls --help

What is the function of grep

grep command (replacing chris with your name) shows the defi nition of your user account in the /etc/password fi le. The last fi eld in that entry shows that the bash shell (/bin/bash) is your default shell (the one that starts up when you log in or open a Terminal window). $ grep chris /etc/passwd chris:x:13597:13597:Chris Negus:/home/chris:/bin/bash You can try a few commands in that shell and type exit when you are fi nished to return to the bash shell.

What's the command to show the date?

show current day, month, date, time, time zone, and year $ date Sat Oct 19 08:04:00 EST 2014

What's the command to show the hostname?

shows your computer's hostname $ hostname mydesktop

What's the command to show files and directories with options?

you can group single-letter options together or precede each with a hyphen, to use more than one option at a time. For example, the following two uses of options for the ls command are the same: In both cases, the ls command is run with the -l (long listing), -a (show hidden dot fi les), and -t options (list by time). $ ls -l -a -t $ ls -lat

You might choose to use different shells for the following reasons:

■ You are used to using UNIX System V systems (often ksh by default) or Sun Microsystems and other Berkeley UNIX-based distributions (frequently csh by default), and you are more comfortable using default shells from those environments. ■ You want to run shell scripts that were created for a particular shell environment, and you need to run the shell for which they were made so you can test or use those scripts from your current shell. ■ You simply prefer features in one shell over those in another. For example, a member of my Linux Users Group prefers ksh over bash because he doesn't like the way aliases are used with bash. Although most Linux users have a preference for one shell or another, when you know how to use one shell, you can quickly learn any of the others by occasionally referring to the shell's man page (for example, type man bash). Bash includes features originally developed for sh and ksh shells in early UNIX systems, as well as some csh features.

Command-line recall (recall a command of the history referencing the number)

■!n—Run command number. Replace the n with the number of the command line and that line is run.(Repeat the command 382 that is date) $ !382 dateWed Oct 29 21:30:06 PDT 2014 ■!!—Run previous command. Runs the previous command line. Here's how you would immediately run that same date command: $ !! dateWed Oct 29 21:30:39 PDT 2014 ■!?string? Run command containing string. This runs the most recent command that contains a particular string of characters. For example, you can run the datecommand again by just searching for part of that command line as follows: $ !?dat? date Wed Oct 29 21:32:41 PDT 2014

Using Shell Variables 1

The shell itself stores information that may be useful to the user's shell session in what are called variables. Examples of variables include $SHELL (which identifi es the shell you are using), $PS1 (which defi nes your shell prompt), and $MAIL (which identifi es the location of your mailbox). You can see all variables set for your current shell by typing the set command. A subset of your local variables are referred to as environmentvariables. Environment variables are variables that are exported to any new shells opened from the current shell. Type env to see environment variables. They can also store values for your shell prompts, the size of your history list, and type of operating system. You can refer to the value of any of those variables by preceding it with a dollar sign ($) and placing it anywhere on a command line.

Expanding commands

The two forms of command substitu-tion are $(command) and `command` (backticks, not single quotes). The command in this case can include options, metacharacters, and arguments. The follow-ing is an example of using command substitution: $ vi $(find /home | grep xyzzy) n this example, the command substitution is done before the vi command is run. First, the find command starts at the /home directory and prints out all fi les and directories below that point in the fi lesystem. The output is piped to the grep command, which fi lters out all fi les except for those that include the string xyzzy in the fi lename. Finally, the vicommand opens all fi lenames for editing (one at a time) that include xyzzy. (If you run this and are not familiar with vi, you can type :q! to exit the fi le.) This particular example is useful if you want to edit a fi le for which you know the name but not the location. As long as the string is uncommon, you can fi nd and open every instance of a fi lename existing beneath a point you choose in the fi lesystem. (In other words, don't use grep from the root fi lesystem or you'll match and try to edit several thousand fi les.)

What is the command to show the type of system hostname and kernel?

The uname command shows the type of system you are running (Linux). When you add -a, you also can see the hostname, kernel release, and kernel version. $ uname Linux $ uname -a Linux unused 3.10.0-121.el7.x86_64 #1 SMP Tue Oct 21 10:48:19 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux

What is the function of who am i

The who am i command shows your username $ who am i chris pts/0 2014-10-21 22:45 (:0.0) En ubuntu lo probe y no hizo nada

What is the result of the command $ ls /usr/bin | sort -f | less?

This command lists the contents of the /usr/bin directory, sorts the contents in alphabeti-cal order (regardless of case), and pipes the output to less. The less command displays the fi rst page of output, after which you can go through the rest of the output a line (press Enter) or a page (press spacebar) at a time. $ ls /usr/bin | sort -f | less

Command-line completion

To attempt to complete a value, type the fi rst few characters and press Tab. Here are some of the values you can type partially from a bash shell: ■Command, alias, or function—If the text you type begins with regular characters, the shell tries to complete the text with a command, alias, or function name. ■Variable—If the text you type begins with a dollar sign ($), the shell completes the text with a variable from the current shell. ■Username—If the text you type begins with a tilde (~), the shell completes the text with a username. As a result, ~username indicates the home directory of the named user. ■Hostname—If the text you type begins with the at symbol (@), the shell completes the text with a hostname taken from the /etc/hosts file TIP;To add hostnames from an additional fi le, you can set the HOSTFILE variable to the name of that fi le. The fi le must be in the same format as /etc/hosts.

Exiting the shell?

To exit the shell when you are fi nished, type exit or press Ctrl+D For example, the su command opens a shell as a new user. Exiting from that shell simply returns you to the original shell

Command-line recall (recall a amount of recent command)

To view your history list, use the history command. Type the command without options or followed by a number to list that many of the most recent commands. For example: $ history 8 382 date 383 ls /usr/bin | sort -a | more 384 man sort 385 cd /usr/local/bin 386 man more 387 useradd -m /home/chris -u 101 chris 388 passwd chris 389 history 8

How to show information about the session id ,group?

Try the id and who commands to get a feel for your current Linux environment, as described in the following paragraphs. When you log in to a Linux system, Linux views you as having a particular identity, which includes your username, group name, user ID, and group ID. Linux also keeps track of your login session: It knows when you logged in, how long you have been idle, and where you logged in from. In this example, the username is chris, which is represented by the numeric user ID (uid) 501. The primary group for chris also is called chris, which has a group ID (gid) of 501. It is normal for Fedora and Red Hat Enterprise Linux users to have the same primary group name as their username. The user chris also belongs to other groups called sales (gid 105) and lp (gid 7). These names and numbers represent the permissions that chris has to access computer resources. $ id uid=501(chris) gid=501(chris) groups=105(sales), 7(lp) Linux distributions that have Security Enhanced Linux (SELinux) enabled, such as Fedora and RHEL, show additional information at the end of the id output. That output might look something like the following: context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

How to find the command located and the type?

Try these few words with the type command to see other locations of commands: which, case, and return. If a command resides in several locations, you can add the -a option to have all the known locations of the command printed. For example, the command type -a ls should show an aliased and filesystem location for the ls command. type -a ls ls is aliased to `ls --color=auto' ls is /bin/ls

Creating and using aliases

Using the alias command, you can effectively create a shortcut to any command and options you want to run later. Examples: $ alias p='pwd ; ls -CF' $ alias rm='rm -i' In the fi rst example, the letter p is assigned to run the command pwd, and then to run ls -CF to print the current working directory and list its contents in column form. The second example runs the rm command with the -i option each time you type rm. (This is an alias that is often set automatically for the root user. Instead of just removing fi les, you are prompted for each individual fi le removal. This prevents you from automatically remov-ing all the fi les in a directory by mistakenly typing something such as rm *.)

Expanding variables

Variables that store information within the shell can be expanded using the dollar sign ($) metacharacter. When you expand an environment variable on a command line, the value of the variable is printed instead of the variable name itself, as follows: $ ls -l $BASH -rwxr-xr-x 1 root root 1012808 Oct 8 08:53 /bin/bash Using $BASH as an argument to ls -l causes a long listing of the bash command to be printed.


Set pelajaran terkait

Social Studies Ancient Greece Assessment

View Set

History 3.3 The Maritime Provinces

View Set

Strength And Conditioning Exam 2

View Set

A Beka: Vocabulary Spelling Poetry V Quiz 08B (English 11)

View Set

Chapter 12 Communication in Organizations Key Concepts

View Set

Driving Academy Review Questions

View Set

Ch. 12. Nutrition Assessment - Jarvis

View Set

Unit 13: Entering the 21st Century

View Set

Pathopharm & Pathophysiology Exam 1 Review

View Set