Главная » Просмотр файлов » UNIX Reference Manual

UNIX Reference Manual (794271), страница 3

Файл №794271 UNIX Reference Manual (UNIX Reference Manual) 3 страницаUNIX Reference Manual (794271) страница 32019-05-08СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Looping is prevented if the first word of the new text is the same as the oldby flagging it to prevent further aliasing. Other loops are detected and cause an error.Note that the mechanism allows aliases to introduce parser metasyntax. Thus, we can ‘alias print ´pr \!∗ |lpr´’ to make a command that pr’s its arguments to the line printer.Variable substitutionThe shell maintains a set of variables, each of which has as value a list of zero or more words.

Some of thesevariables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell’sargument list, and words of this variable’s value are referred to in special ways.4th Berkeley DistributionJanuary 21, 19946CSH ( 1 )UNIX Reference ManualCSH ( 1 )The values of variables may be displayed and changed by using the set and unset commands. Of thevariables referred to by the shell a number are toggles; the shell does not care what their value is, onlywhether they are set or not.

For instance, the verbose variable is a toggle that causes command input to beechoed. The setting of this variable results from the −v command line option.Other operations treat variables numerically. The ‘@’ command permits numeric calculations to be performed and the result assigned to a variable.

Variable values are, however, always represented as (zero ormore) strings. For the purposes of numeric operations, the null string is considered to be zero, and the second and additional words of multiword values are ignored.After the input line is aliased and parsed, and before each command is executed, variable substitution is performed keyed by ‘$’ characters. This expansion can be prevented by preceding the ‘$’ with a ‘\’ except within ‘"’s where it always occurs, and within ‘´’s where it never occurs. Strings quoted by ‘`’ are interpreted later (see Command substitution below) so ‘$’ substitution does not occur there until later, if at all. A‘$’ is passed unchanged if followed by a blank, tab, or end-of-line.Input/output redirections are recognized before variable expansion, and are variable expanded separately.Otherwise, the command name and entire argument list are expanded together.

It is thus possible for the first(command) word (to this point) to generate more than one word, the first of which becomes the commandname, and the rest of which become arguments.Unless enclosed in ‘"’ or given the ‘:q’ modifier the results of variable substitution may eventually be command and filename substituted.

Within ‘"’, a variable whose value consists of multiple words expands to a(portion of) a single word, with the words of the variables value separated by blanks. When the ‘:q’ modifieris applied to a substitution the variable will expand to multiple words with each word separated by a blankand quoted to prevent later command or filename substitution.The following metasequences are provided for introducing variable values into the shell input. Except asnoted, it is an error to reference a variable that is not set.$name${name}Are replaced by the words of the value of variable name, each separated by a blank.

Bracesinsulate name from following characters that would otherwise be part of it. Shell variableshave names consisting of up to 20 letters and digits starting with a letter. The underscorecharacter is considered a letter. If name is not a shell variable, but is set in the environment,then that value is returned (but : modifiers and the other forms given below are not availablehere).$name [ selector ]${name[selector] }May be used to select only some of the words from the value of name. The selector is subjected to ‘$’ substitution and may consist of a single number or two numbers separated by a‘−’. The first word of a variables value is numbered ‘1’. If the first number of a range isomitted it defaults to ‘1’. If the last number of a range is omitted it defaults to ‘$#name’.The selector ‘∗’ selects all words.

It is not an error for a range to be empty if the second argument is omitted or in range.$#name${#name}Gives the number of words in the variable. This is useful for later use in a ‘$argv[selector]’.$0Substitutes the name of the file from which command input is being read. An error occurs ifthe name is not known.$number4th Berkeley DistributionJanuary 21, 19947CSH ( 1 )UNIX Reference ManualCSH ( 1 )${number}Equivalent to ‘$argv[number]’.$∗Equivalent to ‘$argv[∗]’.

The modifiers ‘:e’, ‘:h’, ‘:t’, ‘:r’, ‘:q’ and ‘:x’ may be applied to thesubstitutions above as may ‘:gh’, ‘:gt’ and ‘:gr’. If braces ‘{’ ’}’ appear in the commandform then the modifiers must appear within the braces. The current implementation allowsonly one ‘:’ modifier on each ‘$’ expansion.The following substitutions may not be modified with ‘:’ modifiers.$?name${?name}Substitutes the string ‘1’ if name is set, ‘0’ if it is not.$?0Substitutes ‘1’ if the current input filename is known, ‘0’ if it is not.$$Substitute the (decimal) process number of the (parent) shell.$!Substitute the (decimal) process number of the last background process started by this shell.$<Substitutes a line from the standard input, with no further interpretation.

It can be used toread from the keyboard in a shell script.Command and filename substitutionThe remaining substitutions, command and filename substitution, are applied selectively to the arguments ofbuiltin commands. By selectively, we mean that portions of expressions which are not evaluated are not subjected to these expansions. For commands that are not internal to the shell, the command name is substitutedseparately from the argument list. This occurs very late, after input-output redirection is performed, and in achild of the main shell.Command substitutionCommand substitution is shown by a command enclosed in ‘`’.

The output from such a command is normally broken into separate words at blanks, tabs and newlines, with null words being discarded; this text then replaces the original string. Within ‘"’s, only newlines force new words; blanks and tabs are preserved.In any case, the single final newline does not force a new word. Note that it is thus possible for a commandsubstitution to yield only part of a word, even if the command outputs a complete line.Filename substitutionIf a word contains any of the characters ‘∗’, ‘?’, ‘[’ or ‘{’ or begins with the character ‘˜’, then that word is acandidate for filename substitution, also known as ‘globbing’.

This word is then regarded as a pattern, andreplaced with an alphabetically sorted list of file names that match the pattern. In a list of words specifyingfilename substitution it is an error for no pattern to match an existing file name, but it is not required for eachpattern to match. Only the metacharacters ‘∗’, ‘?’ and ‘[’ imply pattern matching, the characters ‘˜’ and ‘{’being more akin to abbreviations.In matching filenames, the character ‘.’ at the beginning of a filename or immediately following a ‘/’, as wellas the character ‘/’ must be matched explicitly.

The character ‘∗’ matches any string of characters, includingthe null string. The character ‘?’ matches any single character. The sequence ‘[... ]’ matches any one of thecharacters enclosed. Within ‘[... ]’, a pair of characters separated by ‘−’ matches any character lexically between the two (inclusive).The character ‘˜’ at the beginning of a filename refers to home directories. Standing alone, i.e., ‘˜’ it expandsto the invokers home directory as reflected in the value of the variable home.

When followed by a name consisting of letters, digits and ‘−’ characters, the shell searches for a user with that name and substitutes theirhome directory; thus ‘˜ken’ might expand to ‘/usr/ken’ and ‘˜ken/chmach’ to ‘/usr/ken/chmach’. If the character ‘˜’ is followed by a character other than a letter or ‘/’ or does not appear at the beginning of a word, it isleft undisturbed.4th Berkeley DistributionJanuary 21, 19948CSH ( 1 )UNIX Reference ManualCSH ( 1 )The metanotation ‘a{b,c,d}e’ is a shorthand for ‘abe ace ade’.

Left to right order is preserved, with results ofmatches being sorted separately at a low level to preserve this order. This construct may be nested. Thus,‘˜source/s1/{oldls,ls}.c’ expands to ‘/usr/source/s1/oldls.c /usr/source/s1/ls.c’ without chance of error if thehome directory for ‘source’ is ‘/usr/source’. Similarly ‘../{memo,∗box}’ might expand to ‘../memo ../box../mbox’.

(Note that ‘memo’ was not sorted with the results of the match to ‘∗box’.) As a special case ‘{’,‘}’ and ‘{}’ are passed undisturbed.Input/outputThe standard input and the standard output of a command may be redirected with the following syntax:< name Open file name (which is first variable, command and filename expanded) as the standardinput.<< wordRead the shell input up to a line that is identical to word.

Word is not subjected to variable,filename or command substitution, and each input line is compared to word before any substitutions are done on the input line. Unless a quoting ‘\’, ‘"’, ‘’ or ‘`’ appears in word, variable and command substitution is performed on the intervening lines, allowing ‘\’ to quote‘$’, ‘\’ and ‘`’.

Commands that are substituted have all blanks, tabs, and newlines preserved,except for the final newline which is dropped. The resultant text is placed in an anonymoustemporary file that is given to the command as its standard input.> name>! name>& name>&! nameThe file name is used as the standard output. If the file does not exist then it is created; ifthe file exists, it is truncated; its previous contents are lost.If the variable noclobber is set, then the file must not exist or be a character special file(e.g., a terminal or ‘/dev/null’) or an error results.

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

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

Список файлов учебной работы

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