More On Unix Shell

3y ago
21 Views
2 Downloads
211.72 KB
32 Pages
Last View : 17d ago
Last Download : 2m ago
Upload by : Vicente Bone
Transcription

More on Unix ShellSEEM 34601

Shell Operations When a shell is invoked automaticallyduring a login (or manually from akeyboard or script), it follows a presetsequence:1. It reads a special start-up file, typically locatedin the user’s home directory (e.g. /.cshrc), thatcontains some initialization information. Eachshell’s start-up sequence is different.2. It displays a prompt and waits for a usercommand.3. If the user enters a Control-D character on a lineof its own, this is interpreted by the shell asmeaning “end of input” and causes the shell toterminate; otherwise, the shell executes theuser’s command and returns to step 2.SEEM 34602

Shell Operations (con’t) Commands range from simple utilityinvocations, such assepc92: lsto complex-looking pipeline sequences,such assepc92: ps -ef sort ul -tdumb lpSEEM 34603

Shell Operations (con’t) If you ever need to enter a command that is longer than aline on your terminal, you may terminate a portion of thecommand with a backslash (\) character, and the shellthen allows you to continue the command on the nextline:sepc92: echo this is a very long shell command andneeds to \be extended with the line continuation character. Note \that a single command may be extended for several lines.this is a very long shell command and needs to beextended with the line continuation character. Note that asingle command may be extended for several lines.sepc92: SEEM 34604

Executable Files Versus Built-inCommands Most UNIX commands invoke utility programs thatare stored in the directory hierarchy. Utilities arestored in files that have execute permission. Forexample, when you typesepc92: lsthe shell locates the executable program called “ls,”which is typically found in the “/bin” directory, andexecutes it.In addition to its ability to locate and executeutilities, the shell contains several built-incommands, such as echo and cd, which it recognizesand executes internally.SEEM 34605

Input, Output, And Error Channels In the example of the date command,the output was written to the terminal.In UNIX there are three default I/Ochannels that are always assumed to beactive for every command or program: Standard input, known as “stdin”whereby a program expects to find inputStandard output, known as “stdout”whereby a program writes its output bydefaultStandard error, known as “stderr”whereby a program writes errormessagesSEEM 34606

Input, Output, And Error Channels(con’t) By default, the standard input of aprocess is the keyboard and thestandard output and standard errorare the screen.The default I/O channels can beeasily changed on the command lineby using “redirection.”SEEM 34607

Metacharacters Some characters receive special processing by theshell and are known as metacharacters.All four shells share a core set of commonmetacharacters, whose meanings are shown in thetable.When you enter a command, the shell scans it formetacharacters and processes them specially. Whenall metacharacters have been processed, thecommand is finally executed. To turn off the specialmeaning of a metacharacter, precede it with a \character.SEEM 34608

Metacharacters Metacharacters can be listed by using the stty utility with the -a(all) option. Here’s an example:sepc92: stty -a obtain a list of terminal metacharactersspeed 9600 baud;rows 39 columns 142; ypixels 0 xpixels 0intr c; quit \; erase ?; kill u;eof d; eol undef ; eol2 undef ; swtch undef ;start q; stop s; susp z; dsusp y;rprnt r; flush o; werase w; lnext v;-parenb -parodd cs8 -cstopb -hupcl cread -clocal -loblk -parext-ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl -iuclcixon -ixany -ixoff imaxbelisig icanon -xcase echo echoe echok -echonl -noflsh-tostop echoctl -echoprt echoke -defecho -flusho -pendin iextenopost -olcuc onlcr -ocrnl -onocr -onlret -ofill -ofdel -tabssepc92: The in front of each letter means that the Control key must bepressed at the same time as the letter.SEEM 34609

SymbolMeaning Output redirection; writes standard output to a file. Output redirection; appends standard output to a file. Input redirection; reads standard input from a file.*File substitution wildcard; matches zero or more characters.?File substitution wildcard; matches any single character.[.]File substitution wildcard; matches any character between brackets. command Command substitution; replaced by the output from command. Pipe symbol; sends the output of one process to the input of another.;Used to sequence commands. Conditional execution; executes a command if the previous one failed.&&Conditional execution; executes a command if the previous one succeeded.(.)Groups commands.&Runs a command in the background.#All characters that follow, up to a newline, are ignored by the shell andprograms (i.e., signifies a comment). Expands the value of a variable.\Prevents special interpretation of the next character. tokInput redirection; reads standard input from script, up to tok.SEEM 346010

Redirection The shell redirection facility allows you to do thefollowing: store the output of a process to a file (outputredirection) use the contents of a file as input to a process(input redirection)SEEM 346011

Output Redirection Output redirection is handy because it allows you tosave a process’ output into a file so it can be listed,printed, edited, or used as input to a future process.To redirect output, use either the or metacharacter. The sequencesepc92: command fileNamesends the standard output of command to the filewith name fileName. The shell creates the file withname fileName if it doesn’t already exist oroverwrites its previous contents if it already exists.SEEM 346012

Output Redirection If the file already exists and doesn’t have writepermission an error occurs.The following is an example:sepc92: ls files.txtsepc92: cat files.txtprogram1.cprogram1.hSEEM 3460 create a text filefiles.txt storing theresult of ls look at its contents.sortfunc.c13

Output Redirection (con’t) In the next example, I created a file called “alice.txt”by redirecting the output of the cat utility. Withoutparameters, cat simply copies its standard inputwhich in this case is the keyboard—to its standardoutput:sepc92: cat alice.txt create a text file.In my dreams that fill the night,I see your eyes, D end-of -input.sepc92: cat alice.txt look at its contents.In my dreams that fill the night,I see your eyes,sepc92: SEEM 346014

Output Redirection (con’t) The sequencesepc92: command fileNameappends the standard output of command to the file withname fileName. The shell creates the file with namefileName if it doesn’t already exist. In the followingexample, I appended some text to the existing “alice.txt”file:sepc92: cat alice.txtAnd I fall into them,Like Alice fell into Wonderland. Dsepc92: cat alice.txtIn my dreams that fill the night,I see your eyes,And I fall into them,Like Alice fell into Wonderland.sepc92: SEEM 3460 append to the file. end-of-input. look at the new contents.15

Metacharacters (con’t) Here’s an example:sepc92: sepc92: hisepc92: hi filesepc92: echo hi filecat fileecho hi \ file store output of echo in file. look at the contents of “file. inhibit metacharacter. is treated like other characters and output comes to terminalinsteadSEEM 346016

Input Redirection Input redirection is useful because it allows you toprepare a process’ input and store in a file for lateruse. To redirect input, use either the or metacharacter. The sequencesepc92: command fileNameexecutes command, using the contents of the filefileName as its standard input. If the file doesn’texist or doesn’t have read permission, an erroroccurs. In the following example, I sent myself thecontents of “alice.txt” via the mail utility:SEEM 346017

Input Redirection (con’t) sepc92: mail glass alice.txt send myself mail.sepc92: mail look at my mail.Mail version SMI 4.0 Sat Oct 13 20:32:29 PDT 1990Type ? for help. N 1 glass@utdallas.edu Mon Feb 2 13:2917/550&1 read message#1.From: Graham Glass glass@utdallas.edu To: glass@utdallas . eduIn my dreams that fill the night,I see your eyes,And I fall into them,Like Alice fell into Wonderland&q quit mail.sepc92: SEEM 346018

Pipes The shell allows you to use the standard output of oneprocess as the standard input of another process byconnecting the processes together via the pipe ( )Metachacter. The sequencesepc92: command1 command2causes the standard output of command1 to “flowthrough” to the standard in command2. Any number ofcommands may be connected by pipes. A sequence ofcommands chained together in this way is called apipeline.SEEM 346019

Pipes (con’t) Pipelines support one basic UNIX philosophies, which isthat large problems can often be solved by ad smallerprocesses, each performed by a relatively small, reusableutility.The standard error channel is not piped through astandard pipeline, although some shells support thiscapability. In the following example, I piped the output ofthe ls utility to the input of the wcutility to count the number of files in the currentdirectory:sepc92: ls list the current directory.a.cb.ccc.c dir1dir2sepc92: ls wc -w count the entries.5sepc92: SEEM 346020

Pipes (con’t) An illustration of a pipelineIn the next example, I piped the contents of the“/etc/passwd” file into the awk utility to extract thefirst field of each line. The output of awk was thenpiped to the sort utility, which sorted the linesalphabetically. The result was a sorted list of everyuser on the system.SEEM 346021

Pipes (con’t) The commands are as follows:sepc92: head -4 /etc/passwd .look at the password file.root:eJ2S1OrVe8mCg: 0 :1 :Operator: /: /bin/cshnobody:*:65534:60534::/:daemon :*: 1:1:/:sys:*:2:2: :/:/bin/cshsepc92: cat /etc/passwd awk -F: ‘{ print 1 }’ timuucpsepc92: SEEM 346022

Special Local Variables of a Shell Every shell has a set of predefinedenvironment variables that have specialmeanings to the shellNameMeaning HOMEthe full pathname of your home directory PATHa list of directories to search for commands MAILthe full pathname of your mailbox USERyour username SHELL the full pathname of your login shell TERMthe type of your terminalSEEM 346023

Determining Your Terminal’s Type:tset Several UNIX utilities, including the two standardeditors vi (or vim) and emacs, need “know”what kind of terminal you’re using so that theycan control the screen correctly.The type of your terminal is stored by your shellin the TERM environment variable.You may think of environment variables as beingglobal variables for the shell and they can holdstrings.SEEM 346024

Determining Your Terminal’s Type:tset (con’t) Before vi, vim or emacs can work correctly, yourshell’s TERM environment variable must be set toyour terminal type. Common settings for thisvariable include “vtl00” and “vt52.” There areseveral ways to set TERM:Your shell start-up file can set TERM directly bycontaining a line of the form ‘setenv TERM vtl00’ (Cshell) or ‘TERM vtl00; export TERM’ (for Bourne,Korn, and Bash shells). This method of setting TERMis practical only if you know the type of yourterminal in advance and you always log into thesame terminal.Your shell start-up file can invoke the tset utility,which looks at the communications port that you’reconnected to and then set TERM accordingly.Consult the online manual for tset.SEEM 346025

Setting TERM environment variable You can manually set TERM by:sepc92: setenv TERM vt100To display the content of an environmentvariable:sepc92: echo TERMvt100SEEM 346026

How a Shell Finds A Command When a shell processes a command, it first checks tosee whether the command is a built-in; if it is, theshell executes it directly. echo is an example of abuilt-in shell command:sepc92: echo some commands are executed directly bythe shellsome commands are executed directly by the shellsepc92: SEEM 346027

How a Shell Finds A Command If the command in question isn’t a built-in command, then the shell checks whether it begins with a / character. If it does, the shell assumes that the first token is theabsolute pathname of a command and tries to executethe file with the stated name. If the file doesn’t exist or isn’t an executable file, anerror occurs:sepc92: /usr/ucb/lsabc.txtprogram.cpp full pathname of the ls utilitysepc92: /usr/local/bin/nsx/usr/local/bin/nsx: not found a non-existent filenamesepc92: /etc/passwd/etc/passwd: Permission denied . the name of the password file it’s not executableIf it is not an absolute pathname, the shell checks whetherit begins with a path-related character such as or . or .and tries to execute the file with the stated full pathnamesimilar to the above.sepc92: david/demo/game execute the game program under the home directory of the user davidSEEM 346028

How a Shell Finds A Command : PATH If the command in question isn’t a built-in command or afull pathname, the shell searches the directories whosenames are stored in the PATH environment variable.To display the content of an environment variable:sepc92: echo PATH/sbin:/usr/ucb:/usr/local/binEach directory in the PATH environment variable issearched (from left to right) for an executable filematching the command name. If a match is found, the file is executed. If a match isn’t found in any of the directories, then itlooks for the current directory. If it still fails to find thefile, or if the file that matches is not executable, anerror occurs.SEEM 346029

How a Shell Finds A Command : PATH Here is an example:sepc92: echo PATH/sbin:/usr/ucb:/usr/local/bin directories searchedsepc92: lsabc.txtprogram.cpp ls is located in “/usr/ucb/” the result of executing lssepc92: nsxnsx: not found not located anywhereIf the PATH environment variable is not set or is equal tothe empty string, then only the current directory issearched.As a result, to make sure that only the current directory issearched, one can start with metacharacters ./sepc92: ./who only the current directory is searched instead of the built-in Unix commandSEEM 346030

Setting PATH The contents of the PATH variable may bechanged thereby allowing you to tailor thesearch path to your needs.The original search path is usuallyinitialized by the shell’s start-up file (e.g. /.cshrc) and typically includes all of thestandard UNIX directories that containexecutable utilities.SEEM 346031

The which Utility The which utility can show the currentpath of a certain utility found by the shellusing the steps discussed abovesepc92: which ls/usr/ucb/lsSEEM 346032

Most UNIX commands invoke utility programs that are stored in the directory hierarchy. Utilities are . N 1 glass@utdallas.edu Mon Feb 2 13:29 17/550 & 1 read message #1. From: Graham Glass To: glass@utdallas . edu In my dreams that fill the night, I see your eyes,

Related Documents:

Shell Donax TU Shell Spirax S6 ATF UM Shell Donax TV Shell Spirax S6 ATF VM Shell Donax TX Shell Spirax S4 ATF HDX* Shell ATF XTR Shell Donax TA Shell Spirax S2 ATF D2 Shell ATF IID GREASES Shell Retinax CSZ Shell Gadus S4 V45AC Shell Albida HDX Shell Gadus S3 V460D Shell Retinax LX2 Shell

Bash Shell The shell of Linux Linux has a variety of different shells: – Bourne shell (sh), C shell (csh), Korn shell (ksh), TC shell (tcsh), Bour ne Again shell (bash). Certainly the most popular shell is “bash”. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C

Unix 101: Introduction to UNIX (i.e. Unix for Windows Users) Mark Kegel September 7, 2005 1 Introduction to UNIX (i.e. Unix for Windows Users) The cold hard truth · this course is NOT sponsored by the CS dept. · you will not receive any credit at all introduce ourselv

63 shell australia lubricants product data guide 2013 industry industry industry hydraulic fluids shell tellus and shell irus compressor oils shell corena turbine oils shell turbo oils bearing and circulating oils shell morlina electrical insulating oils shell diala gas engine oils shell mysella oil industrial gear oils shell

UNIX system services UNIX kernel in C computer SH The shell (sh) is a program (written in C) that interprets commands typed to it, and carries out the desired actions. The shell is that part of Unix that most users see. Therefore there is a mistaken belief that sh is Unix. sh is an applications program running under Unix

What is a shell? BINP14 Björn Canbäck A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems. Users direct the operation of the computer by entering commands as text for a command line interpreter to

UNIX and POSIX APIs: The POSIX APIs, The UNIX and POSIX Development Environment, API Common Characteristics. UNIT – 2 6 Hours UNIX Files: File Types, The UNIX and POSIX File System, The UNIX and POSIX File Attributes, Inodes in UNIX

ŁVery advanced shell scripting Œ try these courses instead:! fiUnix Systems: Shell Scripting (III) fl! fiProgramming: Python for Absolute Beginners fl bashis probably the most common shell on modern Unix/Linux systems Œ in fact, on most modern Linux distributions it will be the default shell (the shell users get if they