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

W. Joy - An Introduction to the C shell (794270)

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

Текст из файла

----An Introduction to the C shellWilliam Joy(revised for 4.3BSD by Mark Seiden)Computer Science DivisionDepartment of Electrical Engineering and Computer ScienceUniversity of California, BerkeleyBerkeley, California 94720ABSTRACTCsh is a new command language interpreter for UNIX† systems. It incorporatesgood features of other shells and a history mechanism similar to the redo of INTERLISP.While incorporating many features of other shells which make writing shell programs(shell scripts) easier, most of the features unique to csh are designed more for the interactive UNIX user.UNIX users who have read a general introduction to the system will find a valuablebasic explanation of the shell here.

Simple terminal interaction with csh is possible afterreading just the first section of this document. The second section describes the shell’scapabilities which you can explore after you have begun to become acquainted with theshell. Later sections introduce features which are useful, but not necessary for all users ofthe shell.Additional information includes an appendix listing special characters of the shelland a glossary of terms and commands introduced in this manual.IntroductionA shell is a command language interpreter. Csh is the name of one particular command interpreteron UNIX. The primary purpose of csh is to translate command lines typed at a terminal into system actions,such as invocation of other programs. Csh is a user program just like any you might write.

Hopefully, cshwill be a very useful program for you in interacting with the UNIX system.In addition to this document, you will want to refer to a copy of the UNIX User Reference Manual.The csh documentation in section 1 of the manual provides a full description of all features of the shell andis the definitive reference for questions about the shell.Many words in this document are shown in italics. These are important words; names of commands,and words which have special meaning in discussing the shell and UNIX. Many of the words are defined ina glossary at the end of this document.

If you don’t know what is meant by a word, you should look for itin the glossary.AcknowledgementsNumerous people have provided good input about previous versions of csh and aided in its debugging and in the debugging of its documentation. I would especially like to thank Michael Ubell who madethe crucial observation that history commands could be done well over the word structure of input text, andimplemented a prototype history mechanism in an older version of the shell. Eric Allman has also provideda large number of useful comments on the shell, helping to unify those concepts which are present and to† UNIX is a trademark of Bell Laboratories.----USD:4-2An Introduction to the C shellidentify and eliminate useless and marginally useful features.

Mike O’Brien suggested the pathname hashing mechanism which speeds command execution. Jim Kulp added the job control and directory stackprimitives and added their documentation to this introduction.----An Introduction to the C shellUSD:4-31. Terminal usage of the shell1.1. The basic notion of commandsA shell in UNIX acts mostly as a medium through which other programs are invoked. While it has aset of builtin functions which it performs directly, most commands cause execution of programs that are, infact, external to the shell. The shell is thus distinguished from the command interpreters of other systemsboth by the fact that it is just a user program, and by the fact that it is used almost exclusively as a mechanism for invoking other programs.Commands in the UNIX system consist of a list of strings or words interpreted as a command namefollowed by arguments.

Thus the commandmail billconsists of two words. The first word mail names the command to be executed, in this case the mail program which sends messages to other users. The shell uses the name of the command in attempting toexecute it for you. It will look in a number of directories for a file with the name mail which is expected tocontain the mail program.The rest of the words of the command are given as arguments to the command itself when it isexecuted.

In this case we specified also the argument bill which is interpreted by the mail program to bethe name of a user to whom mail is to be sent. In normal terminal usage we might use the mail commandas follows.% mail billI have a question about the csh documentation.My document seems to be missing page 5.Does a page five exist?BillEOT%Here we typed a message to send to bill and ended this message with a ˆD which sent an end-of-fileto the mail program.

(Here and throughout this document, the notation ‘‘ˆx’’ is to be read ‘‘control-x’’ andrepresents the striking of the x key while the control key is held down.) The mail program then echoed thecharacters ‘EOT’ and transmitted our message. The characters ‘% ’ were printed before and after the mailcommand by the shell to indicate that input was needed.After typing the ‘% ’ prompt the shell was reading command input from our terminal.

We typed acomplete command ‘mail bill’. The shell then executed the mail program with argument bill and wentdormant waiting for it to complete. The mail program then read input from our terminal until we signalledan end-of-file via typing a ˆD after which the shell noticed that mail had completed and signaled us that itwas ready to read from the terminal again by printing another ‘% ’ prompt.This is the essential pattern of all interaction with UNIX through the shell. A complete command istyped at the terminal, the shell executes the command and when this execution completes, it prompts for anew command. If you run the editor for an hour, the shell will patiently wait for you to finish editing andobediently prompt you again whenever you finish editing.An example of a useful command you can execute now is the tset command, which sets the defaulterase and kill characters on your terminal − the erase character erases the last character you typed and thekill character erases the entire line you have entered so far.

By default, the erase character is the delete key(equivalent to ‘ˆ?’) and the kill character is ‘ˆU’. Some people prefer to make the erase character thebackspace key (equivalent to ‘ˆH’). You can make this be true by typingtset −ewhich tells the program tset to set the erase character to tset’s default setting for this character (abackspace).----USD:4-4An Introduction to the C shell1.2. Flag argumentsA useful notion in UNIX is that of a flag argument. While many arguments to commands specify filenames or user names, some arguments rather specify an optional capability of the command which youwish to invoke. By convention, such arguments begin with the character ‘−’ (hyphen). Thus the commandlswill produce a list of the files in the current working directory . The option −s is the size option, andls −scauses ls to also give, for each file the size of the file in blocks of 512 characters. The manual section foreach command in the UNIX reference manual gives the available options for each command.

The ls command has a large number of useful and interesting options. Most other commands have either no options oronly one or two options. It is hard to remember options of commands which are not used very frequently,so most UNIX utilities perform only one or two functions rather than having a large number of hard toremember options.1.3. Output to filesCommands that normally read input or write output on the terminal can also be executed with thisinput and/or output done to a file.Thus suppose we wish to save the current date in a file called ‘now’. The commanddatewill print the current date on our terminal. This is because our terminal is the default standard output forthe date command and the date command prints the date on its standard output.

The shell lets us redirectthe standard output of a command through a notation using the metacharacter ‘>’ and the name of the filewhere output is to be placed. Thus the commanddate > nowruns the date command such that its standard output is the file ‘now’ rather than the terminal. Thus thiscommand places the current date and time into the file ‘now’. It is important to know that the date command was unaware that its output was going to a file rather than to the terminal. The shell performed thisredirection before the command began executing.One other thing to note here is that the file ‘now’ need not have existed before the date commandwas executed; the shell would have created the file if it did not exist.

And if the file did exist? If it hadexisted previously these previous contents would have been discarded! A shell option noclobber exists toprevent this from happening accidentally; it is discussed in section 2.2.The system normally keeps files which you create with ‘>’ and all other files. Thus the default is forfiles to be permanent. If you wish to create a file which will be removed automatically, you can begin itsname with a ‘#’ character, this ‘scratch’ character denotes the fact that the file will be a scratch file.* Thesystem will remove such files after a couple of days, or sooner if file space becomes very tight.

Thus, inrunning the date command above, we don’t really want to save the output forever, so we would more likelydodate > #now*Note that if your erase character is a ‘#’, you will have to precede the ‘#’ with a ‘\’. The fact that the ‘#’ character is theold (pre-CRT) standard erase character means that it seldom appears in a file name, and allows this convention to be used forscratch files. If you are using a CRT, your erase character should be a ˆH, as we demonstrated in section 1.1 how this couldbe set up.----An Introduction to the C shellUSD:4-51.4.

Metacharacters in the shellThe shell has a large number of special characters (like ‘>’) which indicate special functions. We saythat these notations have syntactic and semantic meaning to the shell. In general, most characters whichare neither letters nor digits have special meaning to the shell. We shall shortly learn a means of quotationwhich allows us to use metacharacters without the shell treating them in any special way.Metacharacters normally have effect only when the shell is reading our input.

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

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

Тип файла PDF

PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.

Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.

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

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