Docs/SysAdmin/CLI

Материал из Mandriva Russian Community Wiki.

Перейти к: навигация, поиск
CLI - the Command Line Interface

Содержание

[править] Основные команды и Tips

  • Вызов предыдущей комнды: нажмите ctrl-r и начните ввод команды, она будет подгонять символы в соответствии с наиболее часто используемыми командами.
  • Но еще проще: начните набирать команду и нажмите клавишу [PageUp]: он будет показывать самые последние команды, или нажмите ее снова и она покажет следующую за последнее время.
Image:Konsole.png
[username@localhost ~]$ mkdir level1{,/level2{,/level3{,/level4}}}

Это создаст:

| -- level1
|    ` -- level2
|         ` -- level3
|              `-- level4

Конечно, этот простой пример может также быть завершен с: Of course, this simple example can also be accomplished with:

Image:Konsole.png
[username@localhost ~]$ mkdir -p level1/level2/level3/level4

Вместо:

Image:Konsole.png
[username@localhost ~]$ diff file_name1.c file_name2.c

используйте:

Image:Konsole.png
[username@localhost ~]$ diff file_name{1,2}.c

Скажем, у Вас есть множество изображений с одинаковым названием (разные расширения), что Вы сконвертировали в различные форматы (и хотите избавиться только определенных форматов)

Say you have a bunch of images all the the same name (different extensions) that you've converted into all different formats (and want to get rid of only certain formats.

Image:Konsole.png
[username@localhost ~]$ rm -f image_name.{jpg,pbm,gif,xcf}


Пошлите электронное письмо всем пользователям системы:

Image:Konsole.png
[username@localhost ~]$ cat message.txt

[править] Использование цветных выделений

Цвет подсказок нужен, чтобы Вы могли узнать на взгляд, если сессия локальная или удаленная, пользователь или root...

Color prompts let you know at a glance if the session is local or remote, user or root...

Приложение XTerm и все его потомки понимают excape коды ANSI. Эти коды были разработаны Digital для терминалов VT100 и потом были улучшены для более поздних цветных терминалов. Символы при выводе на окно XTerm фильтруются для последовательностей символов, которые соответствуют управляющим кодам ANSI. Не получиться вводить коды напрямую, они работают только на вывод. Самый простой способ проверить - это поменять подсказку bash.

The XTerm application, and all its progeny understand the ANSI excape codes. These codes were developed by Digital for the VT100 terminal, and were further enhanced for the later colour terminals. The characters output to the XTerm window are filtered for sequences of characters that match the ANSI control codes. It's no good trying to type the codes directly; it only works when they are output. The easiest way to experiment is to change the bash prompt.

Попробуйте первый:

PS1="\e[36m\e[44m\u@\h: \W \$"

Это делается в три части: That's made of three parts:

  • Нормальная подсказка: \u@\h: \W \$
  • Настройка цвета переднего плана: \e[36m
  • Настройка цвета заднего плана: \e[44m
  • The normal prompt: \u@\h: \W \$
  • Setting the foreground colour: \e[36m
  • Setting the background colour: \e[44m

Цвета: чёрный:0, красный:1, зеленый:2, желтый:3, синий:4, пурпурный:5, голубой:6, белый:7

Добавьте 30 для смены цвета переднего плана или 40 для смены цвета заднего плана. Чтобы получить другие атрибуты символов используйте: 0:обычный, 1:мерцающий , 4:подчеркивание, 5:жирный, 7:инвертированны. Добавьте 20 чтобы добавить эту возможность.

To get other character attributes use: 0:normal, 1:blink , 4:underscore, 5:bold, 7:inverse. Don't expect blink to blink, but it may do something. Add 20 to turn a feature off individually.

Вы можете использовать жирные окрышенные с 1;ХХm (где ХХ численное значение) и различные цвета для пользователей, the host and the path. Итак, man bash предполагает что непечатные символы должны находиться между \[ и \]. Далее следует пример, который Вы можете поместить в ~/.bashrc :

You can use bold colors with 1;xxm and different colors for the user, the host and the path. Also, man bash suggests that sequences of non-printing characters should be embedded into the prompt between \[ and \]. Here is what I found somewhere that you can put in ~/.bashrc :

LIGHT_RED="\[\e[1;31m\]"
YELLOW="\[\e[1;33m\]"
WHITE="\[\e[1;37m\]"
NO_COLOUR="\[\e[0m\]"
export PS1="[${WHITE}\u${NO_COLOUR}@${LIGHT_RED}\h ${YELLOW}\W${NO_COLOUR}]\\$ "

So much for the colours. But you can do a lot more. To change the title bar use \e]2;my title\a

Если Вы пользуетесь текстовой консолью то все равно можете иметь строку заголовка:

If you are using a text console you can still have a title bar:

PS1="\e7\e[H\e[7m\e[Kmy title\e[0m\e8 $"
  • \e7 - Сохранить позицию курсора
  • \eH - Курсор на строку 1, столбец 1
  • \e[7m - Инвертировать видео
  • \e[K - Erase line to the right - turn whole line to inverse video
  • \e[0m - Обычный видеорежим
  • \e8 - Восстановить позицию курсора

To change the prompt for root, you can test the user ID in .bashrc and set PS1 accordingly:

if (( $UID )) ; then
   pscol='\e[0m'; # user
else
   pscol='\e[7m'; # root
fi
PS1="${pscol}[\u@\h \W]\\$ \e[K"

This works because each invocation of bash has a specific user ID; to change it you start a new invocation. If you want to test something within a single bash invocation you can use the PROMPT_COMMAND variable, which is executed before each prompt is displayed. This example changes to bold if you are outside your home directory:

PROMPT_COMMAND='if [[ ${PWD:0:${#HOME}} == $HOME ]] ; then
   pscol="\e[25m"; # home;
else
   pscol="\e[5m"; # away;
fi;
PS1="${pscol}[\u@\h \W]\\$ \e[K"'

Note the quoting; the whole thing is enclosed in single quotes, so it doesn't get expanded until it's executed. But within that, PS1 is enclosed in double quotes, so $pscol is expanded when PS1 is set.

More details on the control codes may be found here:

The / codes used in PS1 can be found in "man bash" in the "Prompting" section.

[править] Getting The Most Out Of CLI Documentation

( and other tips, tricks and tweaks )

UPDATED: 25 Mar 2005

So you know how to copy and list files, change directories and can get around a bit on a command line. Great, but what happens when you want to learn how to do something else and can't figure out how? If you try to get help from an email list, folks on the list will tell you to use:

Image:Konsole.png
[username@localhost ~]$ man [what ever you are looking for]

or use info pages:

Image:Konsole.png
[username@localhost ~]$ info [what ever you are looking for]

Often however, they may not tell you much else. Why? Because everyone is expected to at least try to find what is needed in documentation before asking questions. That is what the documentation is for. OK great, but how does one go about finding specific information in the seemingly endless sea of documentation available? Such will be the subject of this tutorial.

Note: Examples presented here will be for users of the BASH shell but many of them will be useful in other shells as well. BASH is the default command line shell for Mandriva Linux and many other Linux systems.


[править] Others keep telling me that I need to learn the command line someday. Why would I want to do that?

The command line, also known as a command shell, is where the real power is. This is even true of the leading brand of operating system, although they try to deny the user the command line when ever possible. In any case, every system has problems now and then. Especially as users get more competent and decide to try more powerful tools. Linux has many of the most powerful tools of all. Most of us have heard the phrase, "With great power comes great responsibility." The Linux philosophy is to prepare the user for this since it will happen eventually and troubleshooting is almost always done best at the command line. By convincing users to learn it, we empower them even more. If you've always wondered why there are so many command line junkies out there, here is a page or so of reading that you will find very enlightening:

If you want to start learning all about the BASH shell, I suggest you print this page for quick reference and then move on to this one:

One additional thing you should know right off the bat. This is Linux so there's more than one command shell avialable. It is my feeling that everyone should learn BASH first, though, because of it's pervasiveness. Heck, BASH can be found almost anywhere that has a Unix style environment and even some non-Unix environments as well. For your reseaching pleasure, here is a list of other command shells:

  • Bourne Shell (Ancestor of the BASH shell)
  • C Shell (Supposed to be like writing C code)
  • TC Shell (Supposed to be a "Next Gen" C shell)
  • Korn Shell (Another trusty old standard)
  • Z Shell (Supposed to be the one with the most wiz-bang features)

Note: The info above was gleaned from UNIX Unleashed, System Administrator's Edition: Ch 13


[править] I typed man [what I was looking for] or info [what I was looking for] and despite the fact that I know it is there somewhere, I did not get a suitable response

Much like using a search engine for the first time, it takes a bit of poking about before one gets the hang of searching for stuff in man or info pages. Try some of these commands to get a better idea of where to look and what to do:

Command              Section        Description
-------------------------------------------------------
whatis [something]     (1)          Search for complete words
apropos [something]    (1)          Search for strings
man -k [something]                  Same as apropos 
man -K [something]                  Search for string in *all* man pages (slow but effective). This option also 
                                    allows you to choose to skip sections which the user knows to be wrong.
info --apropos [something] | less   Search info database for information on [something]
q                                   Quit - Ends the program. Works for both info and man. 


[править] How do I navigate through these info pages to find what I need?

Moving within a node:
---------------------
Home                 Go to the beginning of this node.
End                  Go to the end of this node.
SPC                  Scroll forward a page and moves the next node when the end is reached.
DEL                  Scroll backward a page and moves the previous node when the end is reached.
PageUp/PageDown      Scrolls the screen up and down but doesn't move beyond the current page. 
/                    Use "/" to find a specific word on the current page.  Similar to CTRL-F 
                     in a web browser. You can hit "/" and then enter a search word and thereafter
                     "/[enter]" will get you to the next word.
q                    Quit - Ends the program. 

Pay close attention to your status line at the top of the screen. There are links in an info page just like in an HTML page, so in order to get to the next "node" all you have to do is select a link and hit [enter].


[править] I want to print a man page... how can I do that from the CLI?

Here is where you will learn some of the power of the command prompt. Let's say you want to know more about how to use the cat command. You might do something like this:

[njim@enigma 0 root]$ whatis cat
cat                  (1)  - concatenate files and print on the standard output
[njim@enigma 0 root]$ man cat

Then after reading it, you may want to print a copy. Some man pages are pretty long though, so first we want to make sure it isn't too big. What we will do then, is write a short line of chained commands, where one program passes it's output to the input of another program. It will look like this:

[njim@enigma 0 njim]$ man smb.conf | wc -l
6100

Here we used a pipe (i.e. "|") to route the output of man to the wc (A.K.A word counter) command. OK so the man page for the Samba configuration file smb.conf, is 6100 lines long. There are about 80 lines in a page, so let's do a short math problem to find out what printing this would cost us in resources.

[njim@enigma 0 njim]$ expr 6100 / 80
76
[njim@enigma 0 njim]$

Seventy-six pages? I don't think we will be printing this document any time soon. Don't let this discourage you from printing, though. There are plenty of shorter pages, we just need to be aware of the longer ones before sending a print command. Now on to the cat command as originally discussed.

[njim@enigma 0 njim]$ man cat | wc -l
71
[njim@enigma 0 njim]$

Seventy-one lines, so just under a page. We can handle this easily, so let's print it.

[njim@enigma 0 njim]$ man -t cat | lpr
[njim@enigma 0 njim]$

The output of man -t is in a printing language called postscript. If we wanted to have a post script file instead of sending it directly to the lpr (a.k.a LinePRinter), we could put it into a file by using something like this.

[njim@enigma 0 njim]$ man -t cat > cat.ps 
[njim@enigma 0 njim]$

We could also convert it to an Adobe PDF file by using yet another command.

[njim@enigma 0 njim]$ man -t cat | ps2pdf - cat.pdf
[njim@enigma 0 njim]$

OK, now here is a blow-by-blow of the above command.

First, we use man to look up the cat command and convert the output of the man command to printing language using the "-t" option. Then we hand it off to the ps2pdf command for conversion into an Adobe document. The "-" right after ps2pdf tells it that it will be getting it's input from another program instead of accepting it from a user. Of course, cat.pdf is the name of the Adobe document we wind up with.

OK, one last set of tricks that can be done with man pages. We can convert them directly to text with the following commands:

$ man [what we were looking for] | col -b

Of course this can be dumped to a file with...

$ man [what we were looking for] | col -b > nameoffile.txt

or it can be read with...

$ man [what we were looking for] | col -b | less


[править] Uh... how do I actually find something in a long man or info page

I'ts easy if you know the trick. You do it same as you would on a web page. Once you have the page loaded, type a "/" and then the word you want to jump to. Using "n" thereafter will cause you to jump again to the next occurence. Using "N" will cause you to move to the previous occurence. Use "/" again to change the word. BTW, you can use "/" in Mozilla based web browsers also, rather than using CTRL+f. Doing my web page searching this way is how I learned the habit. In a man page, you can also just type "h" for further help on keystrokes.


[править] Isn't there an easier way to manage files from the command line?

Actually there is! Midnight Commander is a command line file management program found on many systems. The command to bring it up is mc. Give it a try. :-)


[править] Don't I need a GUI environment to get email and browse the web? What if I need some information from the Internet, and it is not available? What can I do?

There are text based browsers and email programs that can be used. I use an email program called pine to read email from the command line and there are at least two command line web browsers available, namely links and lynx.

Now I use Firefox for a GUI browser. So if my GUI were broken and I wanted to check and see if I had some useful links in my Firefox bookmarks, I could do something like this.

[njim@enigma 0 njim]$ links .mozilla/firefox/3v6sqvzi.default/bookmarks.html
[njim@enigma 0 njim]$

Now some of the help that may be available is stored on your machine as web pages, so you might also try something like this:

[root@enigma 0 root]$ links /usr/share/doc/HTML/index.html

Some other command line email programs are elm, mutt, sylpheed (as opposed to sylpheed-claws, which is the GUI version) and there is always emacs.

(Note: Sylpheed can send / receive mail from the command line, but it has a modern GTK+2 GUI ! )


[править] I am using a text based browser and need to have more than one page open simultaneously. How can I do this?

You can use your virutal terminals or the screen command. Try some of the following:

What terminal am I currently logged into?

[njim@enigma njim]$ who
njim     tty1         Mar 18 03:28
njim     pts/0        Mar 18 03:28 (spartack.j9starr.net)
[njim@enigma njim]$

So I am logged in from two different points. One is a remote ssh session from spartack.j9starr.net and the other is the first local terminal. There are other local command line terminals, though. You can switch between them by using CTRL+ALT+F? where "?" is any number from 1 to 6. So what you do is hit CTRL+ALT+F1 and log in and start a browser, then hit CTRL+ALT+F2 and log in again and you can start another one and just use the CTRL+ALT+F? keystrokes to switch between terminals. Your X server, if it is running, can be reached by CTRL+ALT+F7. Knowing this can be handy if your X server isn't working right.

Now the screen command is also a very useful tool. With it, I can start quite a number of screens, each running different programs. Try this.

Type screen and then press the space bar to make the license information go away. Next try a few things, like oh, listing some files or something. Then press CTRL+a and then d. You have just detached your screen. Type screen again and again hit the spacebar to make the license information go away. OK, now let's have a look with screen -list.

[njim@enigma njim]$ screen -list
There are screens on:
        11583.pts-0.enigma      (Detached)
        11686.pts-0.enigma      (Attached)
2 Sockets in /mnt/home/njim/tmp.

[njim@enigma njim]$

So the one I am looking at is the "Attached" one. What ever programs I left running in the detached screen are still running and all I have to do to get back there is type this.

[njim@enigma njim]$ screen -r 11583.pts-0.enigma

I have to make sure that I re-attach and exit out of each screen before logging out for the day though, because those screens don't normally go away when you log out! This can be handy for users who want to quit for the day but have a program they want to keep running till the next day. I do CD/DVD burning and Software compiles this way. Log in, start a screen, start the job, detach the screen and then log back out and the program keeps running. :-)


[править] Arrgh! vi has got to be the most difficult-to-use editor in the world

Well you should try and get used to vi as it is the command line editor most often found on Unix based systems. It is very small and very powerful once you've mastered it. In the mean time, I can provide you with some help. Here are some cheat sheets, courtesy of Anne Wilson and if you really can't figure it out, try other editors like joe, aee, e3, emacs or jed instead. You can also use mcedit from Midnight Commander.


[править] I am interested in reading some of the configuration files but I am afraid that I might change one of them accidentally

Use the less command to browse the file. It has no writing capability and was designed for just such a purpose. It will enable you to view text files but not does not support changes of any sort. You could also use any old web browser, command line or otherwise.


[править] This file system is HUGE and I keep getting lost. How can I find out where I am and where I should be going?

The tree command is very helpful with this. Another helpful command is pwd. Here, you will also see an example of using the echo command to print text on the screen for your users to read.

The echo command works like this:

[root@enigma 0 root]$ echo "Echo will print this line on the screen."
Echo will print this line on the screen.
[root@enigma 0 root]$

Below is my example attempt at finding out where I am. It includes the common occurance of what happens when a command isn't installed. Uh... I did this on purpose... honest! ;-)

[root@enigma 0 share]$ echo "Where the heck am I?"
Where the heck am I?
[root@enigma 0 share]$ pwd
/usr/share
[root@enigma 0 share]$ echo "This is where I am."
This is where I am.
[root@enigma 0 share]$ echo "Where do I want to go?"
Where do I want to go?
[root@enigma 0 share]$ tree | less
bash: /usr/bin/tree: No such file or directory
[root@enigma 0 share]$ echo "Oops, I haven't installed that command yet."
Oops, I haven't installed that command yet.
[root@enigma 0 share]$ urpmi tree

installing /mnt/cdrom/media/main/tree-1.4b3-3mdk.i586.rpm
Preparing...                ##################################################
   1:tree                   ##################################################
[root@enigma 0 share]$ echo "Let's try that again!"
Let's try that again!
[root@enigma 0 share]$ tree | less


[править] Safer System Tweaking

Learning is all about making mistakes. Sometimes though, the price of a mistake can be to high. This document is a simple guide to minimizeing the cost of mistakes when trying to learn something new about your Linux box and the powerful tools within it. It's about prevention rather than fixing something that has already broken.

The keywords here are simple and light weight. More advanced users might conisder putting a development style versioning system over certain files and directories but for our purposes, such a system is overkill. Furthermore, the tips mentioned will cover many isues that should be taken care of even with such a system. Haveing a sophisticated versioning system covering /etc will probably not save you from having accidentally deleted an important file in your home directory, for example.


[править] What have I done?

So you logged in as root and did something that messed things up? What was it? Wish you could find out? Here is a link that discusses a simple system for recording the actions, and yes even the viewpoint, of a user.


[править] Hosed Configuration Files

So let's say that I've been makeing changes to a particular configuration file in order to try and get a particular feature of a particular tool or package to work. If one has a lot of trouble, what will eventually happen is that the application or tool stops working all together. We want to start over but the configuration file bears no resemblance to the orriginal and we no longer have a functoning copy of that file. There are some things that can be done to prevent this.

Text editors often have the ability to make backup copies of a document that is being changed. Often, however this feature is disabled or doesn't work exactly the way required to bail us out of this situation. I'll use the vi (a.k.a. vim, a.k.a. gvim ) editor as an example. This editor makes a backup copy of a file and by default names it filename~. Problem is that it keeps using the same backup name so that once we are three or four changes deep, we don't have a copy of the original any more. Another problem is that we probably shouldn't have little *~ files all over the place. They should be kept in a central location where we can manage them, compress them, delete them as they age, etc. I probably don't need a backup copy of a 5 month old config file. So what are we talking about? We are talking about the user's trash directory which is usually ~/Desktop/Trash.

OK, so what we want to happen then, is that we want vi (and also gvim) to move the backup file to a unique name in the user's trash directory right after createing it. This will require some simple modifications to our .vimrc file. If your user doesn't have a .vimrc file, the one that the root user is using is probably fair game, assuming you have access. If you don't have access to the root user's files, I'll show you how to extract a copy from an RPM file later.

OK, this part is easy. All we need to do is add these lines right after the line if has ("autocmd"):


augroup backups

au!

autocmd BufWritePost,FileWritePost * !diff -d <afile> <afile>~ &> /dev/null;if [[ $? == 1 ]];\
then touch <afile>~;mv <afile>~ `mktemp ~/Desktop/Trash/<afile>.XXXXXX`;fi


augroup END

(note the line continuation marker "\")

The first line declares a new group of automatically executed statements. These are called augroups. The second line erases any stray commands. The third line is the key. It delcares a new autocmd line which will be executed right after a buffer write or a file write. Of the files that we might be editing, this command will affect files named *. What comes after the bang (i.e. "!") is a short bash script that moves the backup file, if there is one, to a unique name in the user's trash directory. That way, we can nail the backup file imeadiately after it has been written. The afile is the name of the file that will be affected. That's the file we are, or just finished, editing. So here is what the bash commands would look like in a script if they weren't all crammed together on one line:


#!/bin/bash

#Check and see if there is a difference between the backup file and the file we just saved.
diff -d $1 $1~ &> /dev/null

#If there is a difference, then execute these commands.
#Possible values are 0, for no difference, 1 if there is a difference, or 2 if one of the files is missing. 
if [[ $? == 1 ]];then 

#Updates the file's "last accessed" time.  We'll need this if we use a date based trash managment
#utility. 
touch $1~

#Make a unique temporary file name in the trash directory and then move the file to that name. 
mv $1~ `mktemp ~/Desktop/Trash/$1.XXXXXX`

fi

From now on, when you save a file that already exists the backup will be moved to a unique name in the user's trash directory. If you are using vi rather than gvim, you will actually see these commands being executed.

This has been one example of how to do safer editing with the vi editor. Although vi is probably the most pervasive Unix text editor there is, it is definately not the easiest to use from the command line. Consequently, I hope to collect similar information for other editors and place it here, in this document. Of special interest are the "easier" editors mentioned here.


[править] Trash Directories and utilities

This is especially easy if you don't mind using mktemp to create unique file names. Example:

#!/bin/bash

until [ -z "$1" ]  # Until all parameters used up...
do
        esctarget=`basename "$1"`
        esctarget=`echo "$HOME/Desktop/Trash/$esctarget" | sed 's/\ /\\\\ /g'`

        if [ -d "$1" ]; then

                dirname=`mktemp -d "$esctarget.XXXXXX"`
                dirname=`echo "$dirname"| sed 's/\\\//g'`
                mv -f "$1" "$dirname"

        elif [ -e "$1" ];then 

                filename=`basename "$1"`
                filename=`mktemp "$esctarget.XXXXXX"`
                filename=`echo "$filename"| sed 's/\\\//g'`
                mv -f "$1" "$filename"
        else
                echo "Error condition: No such files or directories found"
                exit 1

        fi

        shift

done
                                          
exit 0


[править] Command Line Help and Tutorials

Want bash help, or are you just curious what all of the hoopla about CLI is all about. Here are some links that just might help.

NOTE: you don't have to be a full on geek to benefit from the CLI. Just learning the basics can go a long way in helping you control your computer, making it do what you want, not what some company says you want.


[править] Other Topics

Личные инструменты
На других языках