Главная » Просмотр файлов » W. Joy - An Introduction to the C shell

W. Joy - An Introduction to the C shell (794270), страница 5

Файл №794270 W. Joy - An Introduction to the C shell (W. Joy - An Introduction to the C shell) 5 страницаW. Joy - An Introduction to the C shell (794270) страница 52019-05-08СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 5)

A complete description of all these mechanisms is given inthe C shell manual pages in the UNIX Programmer’s Manual.2.4. AliasesThe shell has an alias mechanism which can be used to make transformations on input commands.This mechanism can be used to simplify the commands you type, to supply default arguments to commands, or to perform transformations on commands and their arguments.

The alias facility is similar to amacro facility. Some of the features obtained by aliasing can be obtained also using shell command files,but these take place in another instance of the shell and cannot directly affect the current shells environmentor involve commands such as cd which must be done in the current shell.As an example, suppose that there is a new version of the mail program on the system called ‘newmail’ you wish to use, rather than the standard mail program which is called ‘mail’. If you place the shellcommandalias mail newmailin your .cshrc file, the shell will transform an input line of the formmail billinto a call on ‘newmail’. More generally, suppose we wish the command ‘ls’ to always show sizes of files,that is to always do ‘−s’. We can doalias ls ls −sor evenalias dir ls −screating a new command syntax ‘dir’ which does an ‘ls −s’.

If we saydir ˜billthen the shell will translate this tols −s /mnt/billThus the alias mechanism can be used to provide short names for commands, to provide defaultarguments, and to define new short commands in terms of other commands. It is also possible to definealiases which contain multiple commands or pipelines, showing where the arguments to the original command are to be substituted using the facilities of the history mechanism.

Thus the definitionalias cd ´cd \!* ; ls ´would do an ls command after each change directory cd command. We enclosed the entire alias definitionin ‘´’ characters to prevent most substitutions from occurring and the character ‘;’ from being recognized asa metacharacter. The ‘!’ here is escaped with a ‘\’ to prevent it from being interpreted when the alias command is typed in.

The ‘\!*’ here substitutes the entire argument list to the pre-aliasing cd command, without giving an error if there were no arguments. The ‘;’ separating commands is used here to indicate that----USD:4-16An Introduction to the C shellone command is to be done and then the next. Similarly the definitionalias whois ´grep \!ˆ /etc/passwd´defines a command which looks up its first argument in the password file.Warning: The shell currently reads the .cshrc file each time it starts up. If you place a large numberof commands there, shells will tend to start slowly. A mechanism for saving the shell environment afterreading the .cshrc file and quickly restoring it is under development, but for now you should try to limit thenumber of aliases you have to a reasonable number...

10 or 15 is reasonable, 50 or 60 will cause a noticeable delay in starting up shells, and make the system seem sluggish when you execute commands fromwithin the editor and other programs.2.5. More redirection; >> and >&There are a few more notations useful to the terminal user which have not been introduced yet.In addition to the standard output, commands also have a diagnostic output which is normallydirected to the terminal even when the standard output is redirected to a file or a pipe. It is occasionallydesirable to direct the diagnostic output along with the standard output.

For instance if you want to redirectthe output of a long running command into a file and wish to have a record of any error diagnostic it produces you can docommand >& fileThe ‘>&’ here tells the shell to route both the diagnostic output and the standard output into ‘file’. Similarly you can give the commandcommand | & lprto route both standard and diagnostic output through the pipe to the line printer daemon lpr.‡Finally, it is possible to use the formcommand >> fileto place output at the end of an existing file.†2.6. Jobs; Background, Foreground, or SuspendedWhen one or more commands are typed together as a pipeline or as a sequence of commands separated by semicolons, a single job is created by the shell consisting of these commands together as a unit.Single commands without pipes or semicolons create the simplest jobs.

Usually, every line typed to theshell creates a job. Some lines that create jobs (one per line) aresort < datals −s | sort −n | head −5mail haroldIf the metacharacter ‘&’ is typed at the end of the commands, then the job is started as a backgroundjob. This means that the shell does not wait for it to complete but immediately prompts and is ready foranother command. The job runs in the background at the same time that normal jobs, called foregroundjobs, continue to be read and executed by the shell one at a time. Thusdu > usage &‡ A command of the formcommand >&! fileexists, and is used when noclobber is set and file already exists.† If noclobber is set, then an error will result if file does not exist, otherwise the shell will create file if it doesn’t exist.

Aformcommand >>! filemakes it not be an error for file to not exist when noclobber is set.----An Introduction to the C shellUSD:4-17would run the du program, which reports on the disk usage of your working directory (as well as any directories below it), put the output into the file ‘usage’ and return immediately with a prompt for the next command without out waiting for du to finish. The du program would continue executing in the backgrounduntil it finished, even though you can type and execute more commands in the mean time. When a background job terminates, a message is typed by the shell just before the next prompt telling you that the jobhas completed.

In the following example the du job finishes sometime during the execution of the mailcommand and its completion is reported just before the prompt after the mail job is finished.% du > usage &[1] 503% mail billHow do you know when a background job is finished?EOT[1] − Donedu > usage%If the job did not terminate normally the ‘Done’ message might say something else like ‘Killed’. If youwant the terminations of background jobs to be reported at the time they occur (possibly interrupting theoutput of other foreground jobs), you can set the notify variable. In the previous example this would meanthat the ‘Done’ message might have come right in the middle of the message to Bill.

Background jobs areunaffected by any signals from the keyboard like the STOP, INTERRUPT, or QUIT signals mentioned earlier.Jobs are recorded in a table inside the shell until they terminate. In this table, the shell remembersthe command names, arguments and the process numbers of all commands in the job as well as the working directory where the job was started.

Each job in the table is either running in the foreground with theshell waiting for it to terminate, running in the background, or suspended. Only one job can be running inthe foreground at one time, but several jobs can be suspended or running in the background at once. Aseach job is started, it is assigned a small identifying number called the job number which can be used laterto refer to the job in the commands described below. Job numbers remain the same until the job terminatesand then are re-used.When a job is started in the backgound using ‘&’, its number, as well as the process numbers of allits (top level) commands, is typed by the shell before prompting you for another command.

For example,% ls −s | sort −n > usage &[2] 2034 2035%runs the ‘ls’ program with the ‘−s’ options, pipes this output into the ‘sort’ program with the ‘−n’ optionwhich puts its output into the file ‘usage’. Since the ‘&’ was at the end of the line, these two programswere started together as a background job.

After starting the job, the shell prints the job number in brackets(2 in this case) followed by the process number of each program started in the job. Then the shell immediates prompts for a new command, leaving the job running simultaneously.As mentioned in section 1.8, foreground jobs become suspended by typing ˆZ which sends a STOPsignal to the currently running foreground job. A background job can become suspended by using the stopcommand described below. When jobs are suspended they merely stop any further progress until startedagain, either in the foreground or the backgound. The shell notices when a job becomes stopped andreports this fact, much like it reports the termination of background jobs. For foreground jobs this lookslike% du > usageˆZStopped%‘Stopped’ message is typed by the shell when it notices that the du program stopped.

For background jobs,using the stop command, it is----USD:4-18% sort usage &[1] 2345% stop %1[1] + Stopped (signal)%An Introduction to the C shellsort usageSuspending foreground jobs can be very useful when you need to temporarily change what you are doing(execute other commands) and then return to the suspended job. Also, foreground jobs can be suspendedand then continued as background jobs using the bg command, allowing you to continue other work andstop waiting for the foreground job to finish.

Характеристики

Тип файла
PDF-файл
Размер
185,84 Kb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6314
Авторов
на СтудИзбе
312
Средний доход
с одного платного файла
Обучение Подробнее