Download presentation
Presentation is loading. Please wait.
1
BASH (The Bourne Again Shell)
The Bourne Again Shell is both a command interpreter and a high-level programming language. As command interpreter, it processes commands that you enter in response to its prompt. When you use bash as a programming language, it processes groups of commands stored in files called shell scripts. Like other languages, bash has variables and control flow commands.
2
Introduction We will discuss
How to create and run simple shell scripts Introduction to basic aspects of shell programming Command line customization
3
Creating a simple shell script
A shell script is a file that contains commands that can be executed by the shell. The commands in a shell script can be any commands you can enter in response to a shell prompt. In addition to the commands you would ordinarily use on the command line, there are a group of commands, the control structure commands, that find most of their use in shell scripts. The control-flow commands enable you to alter the order of execution of commands in a script as you would alter the order of execution of statements using a typical structured programming language.
4
Running a script/ Making a File Executable
To execute a shell script by giving its name as a command, you must have permission to read and execute the file that contains the script. Execute permission tells the shell and the system that the owner, group, or public has permission to execute the file. It also implies that the content of the file is executable. Use a text editor to create a file.
5
Simple shell script (whoson)
date echo Users Currently Logged in who If we tried to run this script (./whoson), then we would get the error message “ ./whoson: Permission denied” from bash. The shell does not recognize whoson as an executable file and issues an error message. To fix this we use chmod command chmod 764 rwxrw-r--
6
Command Separation and Grouping (NEWLINE & ;)
The NEWLINE character is a unique command separator because it initiates execution of the command preceding it. The semicolon (;) is a command separator that does not initiate execution of command and does not change any aspect of how the command functions. You can execute a series of commnads sequentially by entering them on a single command line and separating each from the next by a semicolon.
7
The \ Character When you are entering a very long command line and you reach the right side of your display screen, you can use a backslash character to continue the command on the next line. The backslash quotes, or escapes, the NEWLINE character that follows it so that the shell does not treat it as the command terminator.
8
The | and & characters Other command separators are the pipe symbol (|) and the background task symbol (&). These commands separators do not start execution of a command but do change some aspect of how the command functions. The pipe symbol alters the source of standard input or the destination of standard output, and the background task symbol causes the shell to execute the task in the background so you get a prompt back right away and can continue working on other things.
9
Examples Example: redux$ a | b | c
In the above example, the shell directs the output from task a to task b and direct’s b’s output to c. Because the shell runs the entire job in the foreground, you do not get a prompt back until task c runs to completion. Example: redux$ ls –l | grep tmp | less This job results in a long listing of the filenames of all the files in the working directory that contain the string tmp piped through less.
10
Running in the background Example
redux$ d & e & f [1] 14271 [2] 14272 Before bash displays the prompt for a new command, it checks to see if any background jobs have completed. For each job that has completed, bash displays it job number, the word Done, and the command line that invoked the job; then bash displays the prompt. When the job numbers are listed, the number of last job started is followed by a + character, and the job number of the previous job is followed by a – character. Any other jobs listed show a space character. After running the last command, bash displays the following before issuing a prompt: [1]- Done d [2]+ Done e redux$
11
Convince Yourself Create a group of executable files named a, b, and c and have each file echo its name over and over say five times. Then run the following command: redux$: a&b&c& What modifications must be done to the above example in order to make it run on fedora?
12
Command Grouping You can use parentheses to group commands. The shell creates a copy of itself, called a subshell, for each group, treating each group of commands as a job and creating a new process to execute each of the commands. Each subshell has its own environment—among other things, this means it has its own set of variables with values that can be different from the subshells. What is the result of running this command: redux$ (./a ; ./b) & ./c
13
Specifying a Shell #! (Sha-bang!)
By putting on the first line of a shell script the command: #!/bin/shell , tells the OS what utility to invoke (bash, tcsh, or zsh). If the first two characters of a script are #!, the system interprets the characters as that follow as the absolute pathname of the program that should execute the script. Examples… redux$ cat ex1 #!//bin/bash echo “This is a Bourne Again Shell script!” #!//bin/zsh echo “This is a Z Shell script!” set person = Mary echo “$person”
14
Comments Comments make shell scripts easier to read and maintain.
If a pound sign (#) in the first character position of a script is not followed by an exclamation point (!), or if a pound sign occurs in any location in a script other than the first character position, the shell interprets it as the beginning of a comment and ignores everything between the pound sign and the next NEWLINE character.
15
Parameters and Variables
Within the shell, a shell parameter is associated with a value that is accessible to the user. Shell variables that you can name and assign values to are user-created variables. One convention is to use only uppercase letters for names of variables that are exported (environmental variables), and to use mixed case or lowercase letters for other variables. You can change the value of user-created variables at any time, and you can make them readonly, so that they cannot subsequently be changed. Using export, makes them accessible to shells and other programs you may fork during the current login session.
16
Example of initializing a variable
redux$ myvar=abc When you want the contents of myvar, you precede it with a $ sign like so: redux$ echo $myvar abc
17
Keyword shell variables
Variables that have special meaning to the shell are called keyword shell variables (keyword variables) and usually have short, mnemonic names. When you start a shell, several keyword variables are inherited from the environment. Among these are HOME, which identifies your home directory, and PATH, which determines what directories the shell searches when you give a command. Most of these keyword variables are set in /etc/profile or .bash_profile found in your home directory. See example_profile file in notes for more…
18
Positional Parameters
When you call a shell script, positional parameters are the command name and arguments. They are called positional because you refer to them by their position on the command line. Although you can reference them they are read-only.
19
Script example for command line arguments
Execution: redux$./cdl a b c d Program: echo all parameters on command line echo arguments are $1 $2 $3 $4 echo the command given was $0 Output: all parameters on command line arguments are a b c d command given was cdl
20
Variables You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it. Example: Hello World! using variables #!/bin/bash STR="Hello World!" echo $STR
21
More on Variables Example: A very simple backup script (little bit better) #!/bin/bash OF=/var/my-backup-$(date +%Y%m%d).tgz tar -cZf $OF /home/me/ This script introduces another thing. First of all, you should be familiarized with the variable creation and assignation on line 2. Notice the expression '$(date +%Y%m%d)'. If you run the script you'll notice that it runs the command inside the parenthesis, capturing its output.
22
Notice that in the above script, the output filename will be different every day, due to the format switch to the date command(+%Y%m%d). You can change this by specifying a different format.
23
Local Variables Local variables can be created by using the keyword local. #!/bin/bash HELLO=Hello function hello { local HELLO=World echo $HELLO } echo $HELLO hello This example should be enough to show how to use a local variable.
24
Conditionals Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an expression. A word about syntax: The base for the 'if' constructions in bash is this: if [expression]; then code if 'expression' is true. fi
25
example if .. then #!/bin/bash if [ "foo" = "foo" ]; then
echo expression evaluated as true fi #TRY IT!
26
conditional example if .. then ... else
#!/bin/bash if [ "foo" = "foo" ]; then echo expression evaluated as true else echo expression evaluated as false fi
27
Conditionals with variables
#!/bin/bash T1="foo" T2="bar" if [ "$T1" = "$T2" ]; then echo expression evaluated as true else echo expression evaluated as false fi
28
LOOPS The for loop is a little bit different from other programming languages. Basically, it let's you iterate over a series of 'words' within a string. The while executes a piece of code if the control expression is true, and only stops when it is false (or a explicit break is found within the executed code. The until loop is almost equal to the while loop, except that the code is executed while the control expression evaluates to false.
29
FOR example #!/bin/bash for i in $( ls ); do echo item: $i done
On the second line, we declare i to be the variable that will take the different values contained in $( ls ). The third line could be longer if needed, or there could be more lines before the done (4). 'done' (4) indicates that the code that used the value of $i has finished and $i can take a new value.
30
A more familiar for example
#!/bin/bash for i in `seq 1 10`; do echo $i done
31
While Loop #!/bin/bash COUNTER=0 while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER let COUNTER=COUNTER+1 done
32
Until Loop #!/bin/bash COUNTER=20 until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER let COUNTER-=1 done
33
Functions As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name.
34
Function Example #!/bin/bash function quit { exit } function hello {
echo Hello! } hello quit echo foo
35
Commentary of above example
Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function If you are not absolutely sure about what this script does, please try it!. Notice that a functions don't need to be declared in any specific order. When running the script you'll notice that first: the function 'hello' is called, second the 'quit' function, and the program never reaches line 10.
36
Functions with parameters
#!/bin/bash function quit { exit } function e { echo $1 } e Hello e World quit echo foo
37
Functions with parameters cont.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.