OPS145 Lab 9 Newversion

From Littlesvr Wiki
Revision as of 04:08, 25 March 2024 by Andrew (talk | contribs)
Jump to navigation Jump to search

Bash scripting

Bash is the shell you've been using in this course to run Linux commands. Bash is also a programming language. It's a special purpose programming language, not something you would write a graphical application in. What you do in a bash script is essentially the exact equivalent of what you would run at a terminal prompt - except you can run all your commands at once, instead of one at a time.

A bash script is a plain text file. The bash programming language is interpreted (as opposed to compiled) - meaning the code you write doesn't need to be compiled before you can execute it.

Setup

The setup for writing a bash script is minimal. You'll need to:

  1. Create the script in a plain text editor: either graphical or on the command line. Usually you save it with a .sh extension, though technically you don't have to.
  2. Make sure you (and anyone else you want to allow to execute the script) have read and execute permissions for the file.
  3. Add a shebang line at the top.

Permissions

Since bash scripts are interpreted (rather than executed outright): you can't actually execute a bash file. In order to execute the commands in a bash script: they need to be read, and interpreted, and executed, by the bash program.

That's why just giving a script execute permissions may not be enough to run it. You need to give yourself read permission, so that the bash program can read your script and execute it.

In fact you don't even need execute permissions to run a bash script. You can run bash, and give it the name of the script as the first argument.

Shebang line

Because bash scripts are interpreted, and extensions are mostly ignored in Linux: the shell you're using to execute your script needs to know what kind of script it is. There are many interpreted programming languages. If you don't make it clear what language your script is written in: there's a chance it will be misinterpreted.

A shebang line for a bash script looks like this:

#!/bin/bash

It has the be the first line in your script.

Anything following this line is regular bash.

hello.sh

Also

  • echo
  • date
  • temp files
  • script2:
    • delete directory
    • create directory tree
  • script3 extended from script2:
    • fill up tree with files
    • create tarball

Submit evidence of your work

After you finish the lab: run the following commands to submit your work:

cd ~
wget http://ops345.ca/check/ops145-lab9-check.sh # Download the check script
chmod 700 ops145-lab9-check.sh # Make the downloaded file executable
./ops145-lab9-check.sh # Run the check script

If it says "Your lab9 has been submitted": make a screenshot, and you're done. If it gives you any warnings or errors: you have to fix them and try the ./ops145-lab7-check.sh command again.