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

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

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

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

We need not worryabout placing shell metacharacters in a letter we are sending via mail, or when we are typing in text or datato some other program. Note that the shell is only reading input when it has prompted with ‘% ’ (althoughwe can type our input even before it prompts).1.5. Input from files; pipelinesWe learned above how to redirect the standard output of a command to a file.

It is also possible toredirect the standard input of a command from a file. This is not often necessary since most commandswill read from a file whose name is given as an argument. We can give the commandsort < datato run the sort command with standard input, where the command normally reads its input, from the file‘data’. We would more likely saysort dataletting the sort command open the file ‘data’ for input itself since this is less to type.We should note that if we just typedsortthen the sort program would sort lines from its standard input.

Since we did not redirect the standardinput, it would sort lines as we typed them on the terminal until we typed a ˆD to indicate an end-of-file.A most useful capability is the ability to combine the standard output of one command with the standard input of another, i.e. to run the commands in a sequence known as a pipeline. For instance the commandls −snormally produces a list of the files in our directory with the size of each in blocks of 512 characters. If weare interested in learning which of our files is largest we may wish to have this sorted by size rather than byname, which is the default way in which ls sorts. We could look at the many options of ls to see if therewas an option to do this but would eventually discover that there is not. Instead we can use a couple of simple options of the sort command, combining it with ls to get what we want.The −n option of sort specifies a numeric sort rather than an alphabetic sort.

Thusls −s | sort −nspecifies that the output of the ls command run with the option −s is to be piped to the command sort runwith the numeric sort option. This would give us a sorted list of our files by size, but with the smallest first.We could then use the −r reverse sort option and the head command in combination with the previouscommand doingls −s | sort −n −r | head −5Here we have taken a list of our files sorted alphabetically, each with the size in blocks. We have run this tothe standard input of the sort command asking it to sort numerically in reverse order (largest first). Thisoutput has then been run into the command head which gives us the first few lines. In this case we haveasked head for the first 5 lines.

Thus this command gives us the names and sizes of our 5 largest files.The notation introduced above is called the pipe mechanism. Commands separated by ‘ | ’ charactersare connected together by the shell and the standard output of each is run into the standard input of the next.The leftmost command in a pipeline will normally take its standard input from the terminal and the----USD:4-6An Introduction to the C shellrightmost will place its standard output on the terminal. Other examples of pipelines will be given laterwhen we discuss the history mechanism; one important use of pipes which is illustrated there is in the routing of information to the line printer.1.6. FilenamesMany commands to be executed will need the names of files as arguments.

UNIX pathnames consistof a number of components separated by ‘/’. Each component except the last names a directory in whichthe next component resides, in effect specifying the path of directories to follow to reach the file. Thus thepathname/etc/motdspecifies a file in the directory ‘etc’ which is a subdirectory of the root directory ‘/’. Within this directorythe file named is ‘motd’ which stands for ‘message of the day’.

A pathname that begins with a slash is saidto be an absolute pathname since it is specified from the absolute top of the entire directory hierarchy ofthe system (the root ). Pathnames which do not begin with ‘/’ are interpreted as starting in the currentworking directory , which is, by default, your home directory and can be changed dynamically by the cdchange directory command. Such pathnames are said to be relative to the working directory since they arefound by starting in the working directory and descending to lower levels of directories for each componentof the pathname.

If the pathname contains no slashes at all then the file is contained in the working directory itself and the pathname is merely the name of the file in this directory. Absolute pathnames have norelation to the working directory.Most filenames consist of a number of alphanumeric characters and ‘.’s (periods). In fact, all printingcharacters except ‘/’ (slash) may appear in filenames. It is inconvenient to have most non-alphabetic characters in filenames because many of these have special meaning to the shell. The character ‘.’ (period) isnot a shell-metacharacter and is often used to separate the extension of a file name from the base of thename. Thusprog.c prog.o prog.errs prog.outputare four related files. They share a base portion of a name (a base portion being that part of the name thatis left when a trailing ‘.’ and following characters which are not ‘.’ are stripped off).

The file ‘prog.c’ mightbe the source for a C program, the file ‘prog.o’ the corresponding object file, the file ‘prog.errs’ the errorsresulting from a compilation of the program and the file ‘prog.output’ the output of a run of the program.If we wished to refer to all four of these files in a command, we could use the notationprog.*This expression is expanded by the shell, before the command to which it is an argument is executed, into alist of names which begin with ‘prog.’.

The character ‘*’ here matches any sequence (including the emptysequence) of characters in a file name. The names which match are alphabetically sorted and placed in theargument list of the command. Thus the commandecho prog.*will echo the namesprog.c prog.errs prog.o prog.outputNote that the names are in sorted order here, and a different order than we listed them above. The echocommand receives four words as arguments, even though we only typed one word as as argument directly.The four words were generated by filename expansion of the one input word.Other notations for filename expansion are also available.

The character ‘?’ matches any single character in a filename. Thusecho ? ?? ???will echo a line of filenames; first those with one character names, then those with two character names,and finally those with three character names. The names of each length will be independently sorted.----An Introduction to the C shellUSD:4-7Another mechanism consists of a sequence of characters between ‘[’ and ‘]’.

This metasequencematches any single character from the enclosed set. Thusprog.[co]will matchprog.c prog.oin the example above. We can also place two characters around a ‘−’ in this notation to denote a range.Thuschap.[1−5]might match fileschap.1 chap.2 chap.3 chap.4 chap.5if they existed. This is shorthand forchap.[12345]and otherwise equivalent.An important point to note is that if a list of argument words to a command (an argument list) contains filename expansion syntax, and if this filename expansion syntax fails to match any existing filenames, then the shell considers this to be an error and prints a diagnosticNo match.and does not execute the command.Another very important point is that files with the character ‘.’ at the beginning are treated specially.Neither ‘*’ or ‘?’ or the ‘[’ ‘]’ mechanism will match it.

This prevents accidental matching of the filenames‘.’ and ‘..’ in the working directory which have special meaning to the system, as well as other files such as.cshrc which are not normally visible. We will discuss the special role of the file .cshrc later.Another filename expansion mechanism gives access to the pathname of the home directory of otherusers. This notation consists of the character ‘˜’ (tilde) followed by another user’s login name.

For instancethe word ‘˜bill’ would map to the pathname ‘/usr/bill’ if the home directory for ‘bill’ was ‘/usr/bill’. Since,on large systems, users may have login directories scattered over many different disk volumes with different prefix directory names, this notation provides a convenient way of accessing the files of other users.A special case of this notation consists of a ‘˜’ alone, e.g.

‘˜/mbox’. This notation is expanded by theshell into the file ‘mbox’ in your home directory, i.e. into ‘/usr/bill/mbox’ for me on Ernie Co-vax, theUCB Computer Science Department VAX machine, where this document was prepared. This can be veryuseful if you have used cd to change to another directory and have found a file you wish to copy using cp.If I give the commandcp thatfile ˜the shell will expand this command tocp thatfile /usr/billsince my home directory is /usr/bill.There also exists a mechanism using the characters ‘{’ and ‘}’ for abbreviating a set of words whichhave common parts but cannot be abbreviated by the above mechanisms because they are not files, are thenames of files which do not yet exist, are not thus conveniently described.

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

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

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

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