OPS 245 Bash Shell Scripting Part 1 Outline
OPS 245 Bash Shell Scripting Part 1
Outline In this lesson you will learn some basic features of scripting in bash. This will help you configure systems by automating repetitive tasks.
Post Installation Tasks A common task after installing a system is keeping a record of the installation. What software is installed? What hardware is it running on? How is it connected to the network? What processes are running? Having answers to these questions makes it easier to expand the network when buying new hardware, and can make diagnosing issues easier.
Post Installation Commands Some commands used to gather information about a system: uname -rv – display kernel version hostname – display the hostname ps -ef – display all processes on the system rpm -q – display packages installed on the system Commonly combined with -a (all), -l (files). Possibly piped | through wc -l to get a count of lines
Gathering Network Information ip address show – display current address ip route show – display routing table nslookup – get default Domain Name Server
Recording Information While you could type each of these commands manually whenever you need that information… And you should do so until you are comfortable with them and understand what they do . . . it is faster and more efficient to gather them together into a script. Then you have one command that does everything you need. You’ll never forget to run one and have to go back. The output will always be in the same order. You can send the output directly to a file.
Running Commands as Root Many of these commands (and others we will use) are not available to regular users. You need to be an administrator to run them. While it is possible to log in as root (if you know the password), it should normally be avoided. Instead we will use the sudo command to temporarily be given elevated privileges. Making the user an adminstrator when we created them allows them to use sudo. Later we will learn to configure this directly.
Scripting Practice The more scripting you do, the better you will get at it. There are numerous options for gaining more experience. You will find numerous examples linked on the wiki e. g. log into matrix and run the command /home/murray. saul/scripting-1
Sh-Bang Line: #!/bin/bash There are numerous scripting languages. In order help us (and the machine) know which language the script is written in, it is common practice to start a script with #! followed by the path to the shell that should run the script. # indicates a comment (aka shhhh) ! (bang) indicates a command from your history. Combining them on the first line of the script has the special meaning of forcing the script to run in that shell (or not run at all, if that shell is not present).
Variables The variables you learned to use on the command line can be used in scripting too. There are three general types of variables: ENVIRONMENT – (e. g. $USER) – Defined by the system. User-defined - (e. g. $myvar) – you create your own custom variables. Either defining them yourself, or obtaining values from the user that runs the script course=OPS 245 read -p “Enter you section” section Positional – (e. g. $1, $2) – arguments passed into a shell script.
Getting Values from Variables Whichever form of variable, you obtain the value stored in it by adding $ before it. echo “This is $course section $section” Note: if the variable is used in the middle of a word, you may have to wrap it in { } echo “This is ${course}. ${section}”
Command Substitution You already learned how to pipe commands together in ULI 101, but you can also use the output from one command as an argument for another command. Wrap a command in $( ) and it gets executed first. e. g. file $(ls) The ls command gets executed first, obtaining a list of all files in the current directory. That list gets used as the arguments for the file command.
Control Flow Statements - Logic Without the ability to make decisions, scripts would always perform the same task. Never changing See menu. bash Logical structures like if statements allow scripts to respond differently to different conditions. Understanding the purpose and use of logical structures will allow you to make scripts that perform useful tasks and respond in a flexible manner.
Decision Making The process of decision making within a script requires that you check a condition. e. g. Do these strings match? Are these numbers equal? Is this file executable? If that condition is true, the script runs some code, it not it doesn't run it. run if 1. bash (but don't look in it yet)
If statements We use special syntax to tell the shell to make a decision: if condition then #Code to run fi Note that the indentation is not required (the shell will interpret it the same either way), but it makes it easier for us to read and understand.
If statements cont. The if tells the shell to check a condition. The code between then and fi (if backwards) is only run if the condition is 'true'. If the condition comes back 'false', the code is not run. Just skip to the next statement after fi. There are three forms the condition can take, but we will only use one for now. if [ condition ] Note there must be spaces around the [ and before the ]
Conditions - Strings Common conditions for strings include String 1 == String 2 Is true if the strings are the same e. g. if [ $USER == root ] Note ==, not = String 1 != String 2 Is true if the strings are different e. g. if [ $PWD != / ]
Conditions - Numeric There are different operators for comparing numbers. -eq #are the two numbers equal? -ne #are the two numbers non-equal? -lt #is the first number less than the second? -gt #is the first number greater than the second? -le #is the first number less than or equal to the second? -ge #is the first number greater than or equal to the second? Now look in if 1. bash
Conditions - Files There also a number of conditions we can check files for. -e filename #does filename exist? -f filename #does filename exist, and is it a 'normal' file? -d filename #does filename exist, and is it a directory? -r filename #can the user id running script read filename (do they have read permission)? -w filename #can the user id running script write to filename (do they have write permission)? -x filename #can the user id running script execute filename (do they have execute permission)? -s filename #does filename have a size other than zero? -O filename #is the user id running the script filename's owner? -G filename #is filename owned by someone in the same group as the user id running the script?
Conditions - ! There is an extra modifier that can be added to a condition to reverse it. ! means not. It turns false into true or true into false. Example: if [ ! -e $filename ] then echo “$filename does not exist” fi
Conditions - ! cont. ! does not really add in anything you could not do without it, but it can make the structure of your conditions a little easier to manage. Suppose the user gives you a file name and your script should create it if it does not already exist. Compare: if [ -e $fname ] then echo -n "" else touch $fname fi if [ ! -e $fname ] then touch $fname fi
If statements - Else Now that we have basic if statements and condition checking we can move on to some more complex issues. What if you want to run some code if a condition is true, but other code if it is false. Perhaps check that a file exists. If it does, do something with it. If it does not exist, warn the user and exit gracefully. You can already do this with two separate if statements. See two. If. bash
If Statements – Else cont. Using multiple if statements in the way two. If. bash does works. It is not outright 'wrong' But it is inefficient. You are checking the same condition twice. There is special syntax to allow us to run a different block of code if the condition evaluates to false.
If Statements – Else part 3 The else keyword, added into an if statement establishes the ending of the previous block of code, and the start of a new one. See if 2. bash Now the code block to run if the condition is true starts at then, and ends at fi or else (whatever it hits first). The new on ends at the fi. This will change once more soon. The else block always ends at fi.
Nested If statements The code that you run inside the block can be as complex or as simple as you need it to be. The interior block can even include its own if statements as long as they are completely contained inside the outer if. See if 3. bash Note the several layers of indentation. The internal if could even have its own else statements (and these could have internal ifs, etc). See if 4. bash
Elif statements An alternative to nesting if statements several deep is to use the elif (short for else if) keyword. This adds the ability to, if the first condition has come back false, check another condition (and if that is false another, and another, etc). See if 5. bash You can include as many elifs as you need, but there can only be one if for each statement. You can leave out the else, but you can never have more then one.
Summary In this lesson you have begun to learn to write scripts in bash. Using variables Sub-shell execution If statements Conditions else Elif These building blocks will form the basis of most scripts and we will continue to expand on them.
- Slides: 27