What is bash scripting?
As you seen already, BASH
is a “shell programming environment”: a way to tell linux how to run commands.
Shell scripts are at the heart of a shell as a programming environment. They allow us to take the commands we repeat frequently and save them in files so that we can re-run all those operations again later by typing a single command.
So how do I make a bash script?
- identify commands you’d like to repeat
- edit a text and insert these commands
- be sure and add “comments” so you know why you inserted those commands and how to use them
- save the file
- tell bash that you want to “execute” the script (ie. run all those commands)
collect your commands
if I want to write information to the screen, I could use echo
:
prompt> msg="TACC Summer Institute"
prompt> echo $msg
TACC Summer Institute
In order to repeat that over and over, let’s create a script using the text editor vi
(that we learned earlier):
prompt> vi first_script.sh
let’s enter the above command as well as some “comments”. Lines starting with “#” are not executed, so we can use them to remind us what or why we’re doing something.
# Print a message
STRING="TACC Summer Institute"
echo $STRING
type <ESC>:wq
to write the changes then quit vi
.
for now don’t worry about the variable named “STRING”. A string
is a type of variable that holds text data.
“execute” (run) the script
How do we execute a script? Let’s try typing file name:
prompt> first_script.sh
-bash: first_script.sh: command not found
prompt> ./first_script.sh
-bash: ./first_script.sh: Permission denied
OOPS!
So those didn’t work because BASH
doesn’t implicitly know when to execute commands. Try:
prompt> bash ./first_script.sh
TACC Summer Institute
shebang “#!”
In order to not have to type bash
each time, let’s edit the file again and insert a #!
(aka shebang) to let bash know what to do (ie. use /bin/bash
to run the script)
prompt> vi first_script.sh
#!/bin/bash
# The first line is a "shebang". This line is a comment.
# Print a message
STRING1="TACC Summer Institute"
STRING2="is great!"
echo $STRING1 $STRING2
now bash
knows that /bin/bash
should execute the commands, but we also need to tell bash
it’s allowed to run that script.
prompt> chmod +x first_script.sh
( recall that chmod
changes the permissions on a file and +x
adds eXecution permission )
prompt> ./first_script.sh
TACC Summer Institute is great!
We can now repeat any given series of commands exactly, allowing for both ease of use and improved reliability.
QUESTION: Why does scripting improve reliability?
Prev BASH scripting | Next VARIABLES | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center