4- Shell Scripting PDF
Document Details
Uploaded by CalmSerpentine8789
The University of Texas at Dallas
Tags
Related
- LPI-Learning-Material-102-500-en.pdf
- UNIX Lectures PDF
- KSS Unit -2.pdf
- ACFrOgBdFOgbtNWXn8CusxCTr3EuZzUjLk8dKSl1CaMNa6nT_EH7UVlB2QlducvVsLc75RSONZZ5nWC7FhzVrlZ3d8Yvz1KMzQGxpMZVyiCSfFHl80__LnIAAzPmjqU6NOciVOAXYvbLyWZZoVBGMLRleux-9Q20izBiA1wSFw==.pdf
- Linuxand shell scripting.docx
- System & Network Administration Scripting & Shell PDF
Summary
This document is a set of lecture notes/slides covering shell scripting basics. It introduces concepts such as commands, variables, and common shell commands. The material is presented in a step-by-step way, emphasizing practical examples and applications.
Full Transcript
4- Shell Scripting Major Features of the Shell Command Execution Filename Substitution I/O Redirection Pipes Environment Control Background Processing Shell Scripts Shell Programs For this chapter, we will use Bourne Shell: sh/bash echo Comm...
4- Shell Scripting Major Features of the Shell Command Execution Filename Substitution I/O Redirection Pipes Environment Control Background Processing Shell Scripts Shell Programs For this chapter, we will use Bourne Shell: sh/bash echo Command Display information to the std output Escape Characters echo Command How to use the echo command $echo “Hi, this is a test.” [RETURN] Hi, this is a test $echo “Hi, \n this is a test.” [RETURN] Hi, \n this is a test. $echo –e “Hi, \n this is a test.” [RETURN] Hi, this is a test. $echo “Hi, \n this is a test.\c” [RETURN] Hi, \n this is a test.\c echo Command Shell Variables Environment variables Local variables Displaying & Removing Variables: set and unset Shell Variables Assigning Values to Variables 1. A shell variable name must begin with a lowercase or uppercase letter and not digit. 2. There are no spaces on either side of the equal sign. Displaying Shell Variables Use echo command to display text and values of shell variables HOME variable Standard Shell Variables PS1 Set to the string used as your prompt sign PS2 Set to the prompt sign that is displayed whenever you press [Return] CDPATH Set to a list of absolute pathnames Affects the operation of the cd (change directory) command Standard Shell Variables SHELL Set to the full pathname of your login shell TERM Sets your terminal type TZ Sets the time zone that you are in Commands Substitution Using the Grave Accent Mark Practice Write a command that writes your login, home directory and today’s date, like the following: Hi, your id is mxb135330 Your home directory is /people/cs/m/mxb135330 Today’s date and time is Mon Jan 28 19:19:19 CST 2015 URL to answer http://goo.gl/cPE71M Answer echo -e "Hi, your id is `whoami`\nYour home directory is $HOME\nToday's date and time is `date`" Sequencing the Commands Using the Semicolon: Enter a series of commands on a command line, separated by semicolons Grouping the Commands Using the Parentheses Group commands together by placing them between a pair of parentheses Background Processing Using the Ampersand – Enter a command followed by &, that command is sent to the background for execution Chaining the Commands Using the Pipe Operator – The shell lets you use standard output of one process as standard input to another – Use the pipe metacharacter | between the commands cat Command – Display text files on screen. cat /etc/passwd – Copy text files. cat oldfile.txt > newfile.txt cp oldfile.txt newfile.txt – Combine text files. cat /etc/hosts /etc/resolv.conf /etc/fstab > new_file.txt – Create new text files. cat > new_file.txt -n : number all output lines -A: display non-printing characters -b: number all output lines, skipping empty lines cut Command Select sections from each line of text file – Print characters by positions cut -c4 file.txt cut -c4,6 file.txt cut -c4-7 file.txt cut -c-6 file.txt – Print fields by delemiter. cut -d' ' -f2 file.txt cut -f2 file.txt sleep and ws Commands sleep: timing a Delay – Causes the process executing it to go to sleep for a specified number of seconds. echo “Hi, ‘sleep 10’ Thanks for waiting” wc: a counting command, takes a file as an argument – wc –w: counts words Practice take a look at /etc/passwd more /etc/passwd Columns are separated by a “:”. The first column is the name of some system users. Use cut command to list only the users column. URL to answer http://goo.gl/cPE71M Answer cut -d':' -f1 /etc/passwd ps Command Displaying the PID – Use to obtain the status of the active processes in the system – Information is arranged in four columns ps Command Displaying the PID ps options kill Command Terminating a Process (no argument) Send a specific signal type. tee Command Splitting the Output: The tee Command – To look at the output of a program on the screen and also store the output in a file grep Command File Searching – To search for a specified pattern in a file or list of files – Good for filtering grep Command grep Options Sort Command Sorting Text Files – Sort the contents of a file into alphabetical or numerical order – Sorts the specified file on a line-by-line basis Content of “junk” file sort Command sort Options sort Command sort Commands Practice Remember /etc/passwd, we want to sort only the user ids listed in reverse alphabetical order URL to answer http://goo.gl/cPE71M Answer cut -d':' -f1 /etc/passwd | sort -r What is a Shell Script A command language – interpreted (not compiled) Shell program files are called shell procedures, shell scripts, or simply scripts – A file that contains a series of commands for the shell to execute Writing a Simple Script Executing a Script Invoking Scripts To make a files executable: – The chmod Command Use. , or add current directory to PATH Example Script Command Line Parameters Command Line Parameters Practice Write a script (script1) that output the following: Hi, the script executed is script1. It is running from directory /people/ cs/m/mxb135330. That same directory contains 7 files and folders URL to answer http://goo.gl/cPE71M Answer Write a script that output the following: echo "Hi, your id is $0" echo "It is running from directory `pwd`” echo "That same directory has `ls -C | wc - w` files and folders" read Command Reading Inputs read Command Comments and Variables The shell recognizes # as the comment symbol; therefore, characters after the # are ignored. Variables – Write the name of the variable, followed by the equal sign and the value you want to store in the variable – No spaces either side of the = sign exit Command Use to immediately terminate execution of your shell program Can have an argument, called exit code By convention code 0 means success Can get exit status: echo $? Practice write a script file (called svi) that does the following – Stores the specified file (first argument) in a directory called keep (create it before hand) in your HOME directory – Invoke the vi editor to edit the specified file Try it with the following:./svi /etc/passwd URL to answer http://goo.gl/cPE71M Answer If-then-else The if-then-else Construct If-then-else The if-then-else Construct If-the-elif The if-then-elif Construct If-then-elif The if-then-elif Construct Testing Different Categories Numeric Values – use the test command to test (compare) two integer numbers algebraically Practice – Accepts three numbers as input (command line arguments) and … – Displays the largest of the three, using an “if construct” – Note: logical operator for “and” is “-a” Output should look like this: URL to answer http://goo.gl/cPE71M Answer String Values – Compare (test) strings with the test command String Values – Compare (test) strings with the test command Testing Files Use the test command to test file characteristics – Size, type, permissions Testing Files: example Parameter Substitution – Lets you test the value of a parameter and change its value according to a specified option Parameter Substitution: Example Arithmetic Operations The expr Command – Arithmetic Operators – Note: spaces between the elements of an expression are necessary ARITHMETIC OPERATIONS The expr Command – Arithmetic Operators – The * (multiplication) and % (remainder) characters have special meaning to the shell, they must be preceded by a backslash [\] Arithmetic Operations The grave accent marks ` and ` surrounding the command are necessary and cause the output of the command (expr) to be substituted. Arithmetic Operations Relational Operators – Relational operators that work on both numeric and nonnumeric arguments. – If both arguments are numeric, the comparison is numeric – If one or both arguments are nonnumeric, the comparison is nonnumeric and uses the ASCII values. – because > (greater than) and < (less than) characters have special meaning to the shell, they must be preceded by a backslash [\] let Command Simpler alternative to the expr command and includes all the basic arithmetic operations for-in-done Construct – Used to execute a set of commands a specified number of times The while-do-done Construct The while loop continues as long as the loop condition is true. The until-do-done Construct – Similar to the while loop, except … – It continues executing the body of the loop as long as the condition of the loop is false – Body of the until loop might never get executed if the loop condition is true STARTUP FILES System Profile – Stored in /etc/profile, 1st to be executed User profile: /etc/profile ~/.bash_profile ~/.bashrc ~/.bash_login ~/.profile At logout: ~/.bash_logout Command Line Editing The alias Command – For shortening the names of frequently used commands or changing command names The history Command – Keeps a list of all the commands you enter during your sessions Restarting the History File – remove your.sh_history or file from your HOME directory. Command Line Editing Practicing the History Command. DEBUGGING SHELL PROGRAMS The Shell Command – Use the sh command with one of its options to make the debugging of your script files easier Options DEBUGGING SHELL PROGRAMS Recall the BOX script file DEBUGGING SHELL PROGRAMS The Shell Command DEBUGGING SHELL PROGRAMS The Shell Command – Run the BOX program with the -v option, and specify some command line arguments.