Chapter-8.pdf
Document Details
Uploaded by LawAbidingCommonsense
Tags
Full Transcript
LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... As CHAPTER EIGHT environment becomes Scripting #!/bin/bash # This is a basic a=Hello b=”Good c=16 (x) echo echo $a $b echo $c you Basics have is already an infinitely seen, extremely more the = command powerful power...
LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... As CHAPTER EIGHT environment becomes Scripting #!/bin/bash # This is a basic a=Hello b=”Good c=16 (x) echo echo $a $b echo $c you Basics have is already an infinitely seen, extremely more the = command powerful powerful Q tool, when but it can script. In this chapter, you will be introduced to the concepts bash of creating your own scripts using the bash scripting script. language. To create a script, though, you must first learn Morning” how to create a file using a text editor to enter all the script’s commands and functions. ©) Text Editors There are a lot of files in a computer system, but the OBJECTIVES Qh line you automate numerous functions at once using a Ba most basic and flexible of them all is the simple text file... + Understand how to use a basic text editor ;. - Be able to create a basic shell script ; ; _. - Be able to create scripts with conditions and 1 oops ; } ; In fact, configuration files and shell scripts are typically ; just text files... ;. Linux users will often modify configuration files. _. and create shell scripts. Therefore, it is necessary to Page 97 of 208 « 48% LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... =: Q understand exactly how to edit text files from within the can do this as the standard user. If the user is attempting shell. To edit text files, the user must be able to start the to view or edit system configuration files, though, then editor and either create a new text file or edit an existing they must act as the root user by either using the su or file. sudo commands. A text editor is a program that simply within Text therefore, (such as English, Spanish, French, etc.), programming they cannot contain any graphics, fonts, emphasis on language (bash, C, Python, etc.), formatted text, program words (such as bold, italics, or underline), or any other or system configuration files, and log files. can include simple ASCII text; the files, including human readable There are a multitude of text editors that can be run familiar with from a GUI-based program like Microsoft within the Linux shell, but the four most popular are vi, Word, LibreOffice, or even Google Docs. emacs, pico, and nano. word processing features that you may Text files contain multiple lines of text that can vary One of the oldest and most popular text editors is vi, in length from 0 characters to multiple pages. These text which is short for “visual”. The vi program is a text-based files can hold many different data types as well, but most editor originally created for the Unix operating system commonly they contain human readable ASCII text. in 1976. It is quite popular with Linux administrators If a user is viewing or editing their own files, they LN language be advanced Aa Text files generally contain five different types of data lets you view and edit documents stored in a plain-text format. files [— who Page 98 of 208 « 48% often edit configuration files, but it is a bit more Q) LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q B&B difficult to use than some of the other more modern text enough features. Nano was developed to fill in this gap editors. in the market between emacs and pico. Nano has more Emacs is an_ extensible, customizable, _ self- features than pico, but it doesn’t have as many as emacs. documenting, and real-time display editor that can be This used is a and allows it to be small and lightweight, while much larger and more complex program than vi, so it maintaining the most needed features from emacs. both from the shell and the GUI. Emacs also gives Each is often not installed in lightweight Linux distributions of the nano a smaller mentioned text file size than editors has emacs still its own by default. Emacs, like vi, was also first created for Unix conventions for displaying information on the screen, back in 1976, and it still remains popular with Linux manipulating administrators. editors are similar up to a point; for instance, one or Pico was designed to work similarly to emacs but removed emacs many to of the advanced create a smaller features from within program and file text, and so on. Most text-mode text more lines at the top or bottom of the display typically show summary information or brief command prompts. size. Refer to the man pages of these text editors or launch This made pico more popular with lightweight Linux them and explore their menus to know more about their distributions, but it’s not nearly as full featured. behavior. Some users found that emacs had too many features After launching a text editor and making changes to (and, therefore, was overly large), while pico didn’t have the file, do not forget to save the file or make a back-up Page 99 of 208 « 49% Aa LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q B&B copy. It is worth taking note that since these programs file starts blank unless it is an existing file. After typing do not feature autosave functions, it is best to regularly the command and pressing enter, the left portion of the save changes to prevent data loss due to interruptions. screen will be lined up with tildes (~). This signifies Additionally, you should launch each of these that those lines have nothing on them. This open file is programs, create a sample file, and get familiar with the also in edit mode. To start typing, press the "i" key on usage of each of these programs to determine which text the keyboard to go into insert mode editor is your favorite—personally, I have always been a characters. Pressing enter moves the cursor to the next bigger fan of pico over vi. line. However, to go back to the previous line or any and start typing other character in the file, the arrow keys do not work; Using Vi and Nano Scan QR code to watch a video for this topic pressing the escape (ESC) key brings back edit mode, allowing for movement using the up and down arrows. Ao There are many text-based editors within Linux, and these are helpful when we need to edit a configuration file or just quickly access a file to make some changes. To run vi, type vi and the filename to be created. For instance, to create the file test1, type vi test1. This Pressing the "x" key deletes characters and pressing the "i" key again allows us to insert or typing characters. There are a couple of useful shortcuts to more easily manipulate vi in edit mode. The caret (4) brings the cursor to the beginning of the line. Typing a number and w, for example "3w", brings the cursor three words Page 99 of 208 « 50% Aa Q) LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q B&B forward while a number and b, for example "2b", brings shown, if not blank. At the bottom are some commands. the cursor two words back. To skip lines, enter a number Commands that start with a caret (4), such as AG, are and capital G; for example, entered by pressing the CTRL key and then hitting the "50G" brings the cursor to the 50th line in the file. Pressing the ":" key then typing G, and this brings up Help, which "set nu" replaces the tildes with line numbers to more Compared to vi, nano is already in edit mode. The arrow easily identify lines. To undo a previous action, typing keys work, "u" will undo it. To save the file, press ":" then type "w" to just like in a word processor. And, similarly, text can be save the information to the file or "wq" to save and quit. copied and pasted. It also has a spell checker and has Typing "q!" at that prompt discards any edits and quits undo and redo. Changes on the file are saved by pressing vi. Vi’s man pages will show more commands on how to AO, and 4X exits the program. With these features, nano properly use it. has more functions and is more convenient than vi, and Running nano is just the same as vi; typing nano and the filename brings up the editor and opens the file. Once more we can use it for those quick file edits and configuration changes. Shell Scripting information than vi. For example, the program’s name and the version is at the top left. The file’s name is at the top center. The file’s contents is also file. and you can insert and delete characters nano shows up, it looks more like a command program. It shows is like a man A program written in an interpreted language, typically associated with a shell or a compiled program, Page 100 of 208 « 50% Aa Q) LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED is known as a script. In Linux, many scripts are created as shell scripts Q The first line begins with two characters (#!). These two characters are a special code that tells the Linux or another shell. Shell scripts are written by users to kernel that this is a script and that the rest of the line help automate tedious, repetitive tasks or to perform should be treated as a pathname to the program that will new and complex tasks. Most distributions use built- interpret this script. In this script, it is the path /bin/ in scripts to perform many of the startup functions in bash, which is the path to the bash shell program. system. administrators Mastering because are associated = with bash a Linux since they RESOURCE TO PASSING THE LPI® LINUX... scripting is important it will help in managing for Within a shell script, the pound symbol or hash mark the (#) is considered a comment character. This causes the script utility to ignore this line, but the kernel still reads startup process of a system. Shell scripts are plain-text files that are created in text it.On most Linux systems, /bin/sh is a symbolic link that editors such as vi, emacs, nano, or pico. A shell script points to /bin/bash, but it can also point to another shell. begins with a line that identifies the shell that should be If a user specifies the script as using /bin/sh instead used to run it. Consider the following simple script: of /bin/bash, this almost certainly guarantees that any Linux system will be able to execute the script since they #!/bin/bash all have a shell program to run the script. If it is a simple echo “Hello World!” bash script, the script can be run in most other shells. Page 101 of 208 « 51% ££) Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q ££) Unfortunately, if the script is more complex, then it will in scripts. This means that other programs can also be need a specific shell or else it could fail. run from within a script. After writing the shell script, we must modify the Most of the commands that a user enters in the shell text file to ensure it is now an executable file within the prompt are external commands. All these programs are operating system by using the chmod located in /bin, /usr/bin, and other directories within command. The use of chmod will be covered in Chapter 12 (Ownership the and Permissions). commands, can be run by simply using their names within script. As you begin to create shell scripts that are lengthier filesystem. the These programs, If needed, as we well can as also internal specify and more complex, you will want to have a good text parameters for each of these programs in a script. For editor program. If using a graphical desktop, KWrite and instance, gnome’s gedit editors are excellent for creating text shell file from Downloads to Documents, launching an xterm scripts. However, if working from a command line, then window, vi, emacs, pico, or nano can be used instead. program inside the GUI: consider the following script for copying and then starting up the KMail mail reader Using Commands in Scripts #!/bin/bash The simplest use of a script is to run a series of commands without user intervention. Commands built into the shell and external commands can both be used cp ~/Downloads/file.txt ~/Documents/file.txt /usr/bin/xterm & /usr/bin/kmail & Page 102 of 208 « 51% a Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED Aside from the first line identifying it as a script, RESOURCE TO PASSING THE LPI® LINUX... character instructs the shell to go =: on to Q the [— next the script looks just like the commands that a user line without waiting for the first command would these three executing. If the ampersand was not provided, the first tasks manually. The only exception is that this script xterm will open, but the KMail program will not open lists the complete paths to each program. This is usually until the xterm program is closed. type into the shell to accomplish not strictly necessary (as shown by the line with the cp command), but listing the complete path ensures Although script can launching save time several during the programs startup to finish from one of a system that the script will find the programs even if the PATH or program, there are some situations where the user environment variable changes. If the script produces an will want to wait for one line of the script to finish error when run (such as “No such file or directory error before for running a command”), you can help locate the program by starting the next line. This a series of programs is common that manipulate when data running the “which” command to locate the path. For from the previous command in some way. These scripts example, if you needed to find the path to the xterm typically do not include the ampersands at the ends of program, entering “which xterm” at the shell prompt the commands should return “/usr/bin” as its path. another or may even rely on the output from the first In the basic script provided, notice that each line command. in the example script ends in an ampersand (&). This Page 103 of 208 « 52% because one command must run after Aa LN LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... While program a script can use any command within it, there are certain commands or that The find command finds on its filename, ownership, a particular = Q file based or other characteristics. If administrators commonly use within a script to conduct an administrator needs to locate a certain pattern of certain functions. information within the contents of our files, they use The command echo command in a script. The is probably echo the command most used displays a message to the user on the screen within the terminal. the grep command instead. The grep command can also display the lines from within a provided file that match the search string. For example, the script may start with a message to the Variables user that says, “Please wait, the script is running...”. This type of message is displayed using the echo command. Another way to expand the usefulness of your When repetitive file maintenance tasks need to be scripts is to use variables. A variable is a placeholder for automated, we use the ls (list), mv (move), cp (copy), and a value to be determined at the script’s execution time. rm (remove) commands. The value of a variable can be passed as parameters to a When text needs to be extracted from a specific field within a file, we heavily use the cut command. script, generated internally within a script, or extracted This from the script’s environment. An environment is a set is especially useful when working with a preformatted of variables, including items like the current directory text file, like a command separated value (CSV) file. Page 104 of 208 « 52% Ba Qh LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED or search path for running programs that a program can access. Variables that are passed to the script are known as RESOURCE TO PASSING THE LPI® LINUX... numbers begin with $0 (representing the name of the script), then go to $1 (the first parameter), then to $2 (the second parameter), and so on. Consider the following script and try to determine what functions are being performed. If you do not understand a command, use the man command to learn more about it. When you think you understand the script, keep reading to see if you understood it properly. #!/bin/bash useradd -m $1 passwd $1 mkdir -p /shared/$1 Q ££) chown $1.users /shared/$1 chmod 755 /shared/$1 In -s /shared/$1 /home/$1/shared chown $1.users /home/$1/shared parameters or arguments. They are represented in the script by a dollar sign ($) followed by a number. These = The script first creates an account using the first argument given to the script as the username. The script then changes the account’s password and creates a directory in the /shared directory corresponding to the account name, which again is received as the first parameter from the user running the script. The ownership of this newly created directory is then given to this new user account, and its permissions modified to give the user read, write, and execute permissions. Next, the script sets a symbolic link to that directory from the new user’s home directory and provides the new user account ownership over this folder in the home directory. Page 105 of 208 « 53% Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED If you didn’t understand everything in this script RESOURCE TO PASSING THE LPI® LINUX... = Q display, such as the prompt for the new password to right now, that is perfect normal since some of these be entered. All the other commands background with no user interaction or knowledge. This By the and programs are new to you at this point. end of this book, though, you should commands are run in the feel is referred to as silent operation. For this reason, many comfortable reading a script like this, or even writing script writers will add display notes into their scripts one yourself. using the echo command so that information can pass To use this script, a user would simply type the name back to the user during the operation. In effect, this of the script, the new username, and enter the desired script simply replaced seven individual commands with password twice, as shown in this excerpt below: a single script. For each command, the first parameter DionTraining:Documents jason$./user_script.sh jasondion (jasondion) was used as a variable to prevent the user Changing password for jasondion from needing to reenter the new username each time. New password: Retype password: Conditional Expressions Password for jasondion changed by jason By default, a script will execute all the commands DionTraining:Documents jason$ listed from the first line to the last line, but sometimes When the script runs, the only thing displayed to the screen is whatever the commands normally would it is helpful to skip lines based on certain circumstances. To achieve this, we use conditional expressions. Page 106 of 208 « 53% ££) Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED Conditional expressions enable a script to perform one of several actions depending on what conditions have been met or the value of a variable. The if command allows the given conditional expression that is placed within brackets after the if keyword, script and to it then actions, depending evaluate perform on whether a a one of two different certain condition is true or false. RESOURCE TO PASSING THE LPI® LINUX... as a whole Q =: to be considered true. When —) we use the logical OR, if either side of the operator is true, then the condition as a whole is also considered true. Consider the demonstrates the following if script command fragment that and _ conditional expression: if [-f /tmp/tempfile.txt] then echo “/tmp/tempfile.txt was found; aborting script.” For example, the file exists condition (-f) is true if file exists and is a regular file. The file exists and isn’t exit fi empty condition (-s) is true if the file exists and has a size greater than O. The “string1 == string2” condition is true if the two strings have the exact same values. This basic conditional evaluates whether the file (tempfile.txt) exists within the /tmp directory. If the file These conditional statements may also be combined exists, then the condition is true, and the “then” branch with the logical AND (&&) or the logical OR (||) operators. will When conditionals combine with the logical AND, then command, both sides of the operator must be true for the condition instead found that the file does not exist, then the echo Page 107 of 208 « 54% execute to display the message using the echo and the script will exit. If the conditional Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library and exist commands A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... are skipped, and the if condition = Q Another useful test condition is to use the output ends when the fi command is reached. The fi command of a command simply shows the end of an if command statement block, pseudocode: as the test case, such as the following as shown above. A conditional, such as the one above, may be useful if your script creates a file when it runs. If you check if the file already exists at the beginning of the script and it if [command] then [additional commands] fi tests true, then this indicates that the script was already In the pseudocode above, the additional commands or is still running. The if command also supports using the keyword test instead of the brackets, if desired. The variant would also work: following will only run if the command in the test condition executes successfully. If the command returns any error codes, then the additional commands simply would be skipped during the script’s execution. The if command also supports the ability to define if test -f /tmp/tempfile.txt then echo “/tmp/tempfile.txt was found; aborting script.” exit what commands should run if the condition is not met. This is often read as “if, then, else”. For example, you fi Page 108 of 208 « 54% ££) Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library may hear programmers A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q and script writers say, “If the choices with two outcomes, this is sometimes limiting. condition is true, then do this, else (otherwise) do that.” For example, if you create a script that displays four choices to the screen as part of a menu option to the user if [command] running the script, the user then enters a number, 1, 2, then 3, or 4, and the script runs a certain command [do this command] based on that number. Using the if-then-else command would else [do that command] require a fairly messy fi pseudocode: This type of coding will cause only one of the two branches to execute: either the then or the else. This is useful when a programmer needs to allow the program to make a choice in which commands to run or what files to operate on based on a certain condition. It is important to note above, multiple commands if [$userchoice == 1] then [do command #1] else if [$userchoice == 2] then that in the pseudocode or lines can be added into [do command #2] else each branch of the then-else, as needed. if [$userchoice == 3] then While the if-then-else works well for conditions and Page 109 of 208 « 55% [do command #3] decision tree, as shown in this ££) Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... else if [$userchoice == 4] 3) [docommand #3];; 4) [docommand #4];; = Q ££) then [do command #4] Generally, else a case each pattern shown echo “Error — User didn’t enter 1, 2, 3, or 4.” statement uses a variable, and before the right parenthesis is a possible value of that variable. In the example above, we While this pseudocode is functional, these nested if- then-else statements are rather clumsy and confusing to understand. Luckily, shell scripting provides us with a suitable alternative, known as a case statement, for scenarios where there are multiple possible outcomes. Consider the following pseudocode using a case statement that performs the same function as the nested if-then-else above: expect the user to input Each set of commands [docommand #1];; 2) [docommand #2];; ends with a double semicolon This allows multiple commands to be run from within each matching case to the value entered by the user in $userchoice. At the end of the case, we use the keyword esac, which is case spelled backwards, just like fi was used for if. ($userchoice 1) of 1, 2, 3, or 4. to signify the end of the actions for that specific case. When case $userchoice in a value using in the a case example statement, above) the variable simple finds the matching case (for example, 3) and executes that single line until it reaches the double Page 110 of 208 « 55% semicolon. Once the Aa LN LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q double semicolon is reached, the script jumps to the line following loop and try to determine what it will cause after the esac keyword. when the user executes this script. If no matching case value is found, then none of the statements will execute, and the #!/bin/bash script resumes operation after the esac keyword. for xin ‘Is *.txt’; do Loops cat $x done So far, all the scripting components covered will only execute a single time. For example, if an if-then- else or case is considered and the test case doesn’t match it currently, it will be skipped and never executed. Unfortunately, sometimes it is important to do things multiple times or to test a condition multiple times to see if the condition has changed. To do this, we use a special structure known as a loop. A loop allows a script to perform the same task repeatedly until a particular condition is met or until a certain condition is no longer true. Consider the In this example, the loop will execute once for every item returned by the command ‘ls *.txt’. Therefore, let’s assume there are 3 files in the current directory: foo1.txt, foo2.txt, and foo3.txt. When this script is executed, the for loop will first run ‘ls *.txt’ and receive a list of 3 files that contain the file extension of.txt. Since there are three files, this loop will execute 3 times. The first time through the loop, the command ‘cat foo1.txt’ is run. This will cause the contents of the foo1.txt file to display on the screen. The Page 111 of 208 « 55% ££ Aa W LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED second time through the loop, the command ‘foo2.txt’ will run, and the contents of foo2.txt will display on the RESOURCE TO PASSING THE LPI® LINUX... Q —) for x in ‘seq 1 3 10’; do echo $x screen. Then, the loop willrun a third time, and this time done the contents of foo3.txt will display to the screen. Since DionTraining:Documents jason$./loop.sh there are no more.txt files in the current directory, the loop will end. Instead of using a command like ls to set the number of times the loop will run, the programmer can DionTraining:Documents jason$ also use the seq command. The seq command generates a list of numbers, starting from the first argument and continuing up to the last argument. If three arguments are given to seq, then it will treat them as the starting value, the increment value, and Considering the following output: DionTraining:Documents jason$ cat loop.sh #!/bin/bash the ending value. This output shows the contents of the loop.sh script. This is a bash script, as shown by the first line (#!/ bin/bash). The loop uses the seq command to create the number of times to execute the loop. Each time the loop executes, the number (x) is displayed to the screen and then a new line is created. Since the seq command has three inputs, the counting will begin at 1, add 3 each time through the loop, and end at 10. The example above Page 112 of 208 « 56% Aa LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... shows the output, with 1, 4, 7, and 10 displayed to the of loop called a while loop. A while loop executes the commands within the loop repeatedly as long as the condition being tested remains true. Q Functions user’s screen. In addition to the for loop, there is also another type = Scripts also support the creation of functions within them. These functions perform a specific subtask and can be called by name from within other portions of the script. Functions are created by placing parentheses after the function name, then enclosing the commands that #!/bin/bash will run as part of the function within curly brackets, as while [test condition] shown in the pseudocode below: do [commands to execute] Done #!/bin/bash myfunction() { There is another loop called an until loop. The until loop works like the while loop, except the until loop [commands to execute] } executes continually as long as the condition remains false. In addition to the name (myfunction) shown above, the script’s writer can optionally add the keyword function (as in, function myfunction) to identify that Page 113 of 208 « 56% ££) Aa LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q Ba section of the script as a function, but this is completely Every script, like every good story, has a beginning, optional. Once the function is created in the script, it can a middle (or body), and an end. That end, though, can be referenced from anywhere else in the script as ifit was come before the script reaches the very end of the script’s an ordinary internal or external command. content, and as demonstrated in our if-then-else example Functions are useful for creating modular scripts earlier in this chapter. Regardless can increase ends, it will return an exit value back to the shell to the readability and efficiency of a script. For example, if the script needs to perform the of when the script indicate it finished its execution. A same computation ten different times throughout it, the script’s default return exit value is the exit computation can be placed in a function, which can then value of the last command the script executed. This is simply be called directly when needed. represented in the shell by the variable $>. The exit value Please note, a function cannot run outside of the script since it isn’t a true program or command. can be controlled, though, and it is possible to exit from Also, the script at any point by using the exit command. Used functions do not run in the order they appear in the without any options, exit causes immediate termination script, but instead they run anytime their name appears of the script, with the default exit value of $?. This can within the script’s main body. be useful in error handling or in aborting an ongoing The Exit Value Qh operation when needed. If the script detects an error or Page 114 of 208 « 57% Q) LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... = Q if the user selects an option to terminate, the script can termination, it will reset $termcause to a non-zero value. include an exit call to quit prior to the script crashing. Any numeric codes may be used here since there is no set If the script instead sends a numeric value between 0 meaning for such codes by default. Whenever the script and 255 to the exit command, then the script terminates reaches a condition where it should exist, it will simply and returns the specified value as the script’s exit value. use “exist $termcause” to exit and return the value of the This is a useful feature that can signal a particular error $termcause variable back to the shell as the exit value. if the script is being called by another script or program. Creating a Script For example, the script may exit with a value of 1 to Scan QR code to watch a video for this topic signify that an invalid input was provided to the script, It is time to put together previously discussed script or a value of 2 to signify that an output file doesn’t exist. The options are limitless and simply left up to the components script’s writer to decide the values and their meaning. simple script, we will use the nano command and create For example, a variable the script’s ($termcause) to designer hold the might value create returned into a complete basic script. To create a a script named logic.sh by typing "nano logic.sh" at the terminal prompt. Start by commenting the first few during the script’s termination. When the program first lines using hashtags or the pound (#) sign. In this case, !/ executes, the value of $termcause will be set to equal 0, bin/bash and Simple logic test display. and then, if the script detects a problem that will cause #!/bin/bash Page 115 of 208 « 57% ££) Aa LN LINUX ESSENTIALS (010-160): QO Kindle Library A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... Q # Simple logic test and display fi Start by using an if command. If the first argument is going to equal 1 ($1 if[ $1 =‘2’] = '1'), the system will display then echo The argument entered was 2 the next statement (then) by using echo "The argument entered was exit 1". An exit is placed, and the fi command ends the loop. The second if command else in the script shows that if the next argument is going to equal 2 ($1 = '2'), the system will display the next statement (then) by using echo "the argument entered was 2", and an exit is placed. Next comes an else command to be used for cases other than the previous two arguments (the number entered is neither 1 nor 2) to display by using echo “the argument entered was not 2". It is also exited, and an fi ends the loop. if[$1 =1'] echo The argument entered was not 2 exit fi Make sure to save the script by pressing 4O, and then press 4X to exit to the terminal prompt. Change the permissions of the file to make sure it can run. Type "chmod 755 logic.sh" to make the file executable. Typing "./logic.sh 1" should satisfy the first if statement and should display "The argument entered was 1" and so on. However, this simple script assumes that there is an argument entered and that there is only one argument. then echo The argument entered was 1 Page 116 of 208 « 58% —) Aa LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... Otherwise it will throw errors when no argument is made, such as typing "./logic.sh". It will return an error: = Q also exits, and the loop ends with the fi command. This portion of the script checks how many arguments there are. If you don't have exactly one argument, the system diontraining@work: ~/Documents/scripts$ chmod 755 logic.sh diontraining@work: ~/Documents/scripts$./logic.sh 1 The argument entered was 1 diontraining@work: ~/Documents/scripts$./logic.sh 2 quits the script. Now the script should run without throwing any no matter argument is supplied. errors, how many or what The argument entered was 2 diontraining@work: ~/Documents/scripts$./logic.sh 3 #!/bin/bash The argument entered was not 2 # Simple logic test and display diontraining@work: ~/Documents/scripts$./logic.sh 0 The argument entered was not 2 if[ $#!=1] diontraining@work: ~/Documents/scripts$./logic.sh then echo “Usage - This script requires one argument that is a./logic.sh: line 4: [: =: unary operator expected number.”./logic.sh: line 10: [: =: unary operator expected exist The argument entered was not 2 diontraining@work: ~/Documents/scripts$ if[$1=‘1'] then echo The argument entered was 1 The first thing to do is to create a check for the exit number of arguments. If it doesn't equal 1 (S# != 1), then fi it will display the usage instructions by using echo. This if[ $1 = 2] then Page 117 of 208 « 58% Ba LINUX ESSENTIALS (010-160): A TIME COMPRESSED RESOURCE TO PASSING THE LPI® LINUX... echo The argument entered was 2 exit else echo The argument entered was not 2 exit fi There is a bunch of things that we can do with scripts, as scripts can be as simple as the one mentioned here, or they can carry out complex logic flows. By adding in these logic steps when creating a script, we can test conditions by using if, then, and else to find out what is going on and to let the computer do the work. Page 118 of 208 « 59% = Q Ba