Skip to content

Create an executable script

Objectives

  • Create an executable bash script
Notes for teachers

Teaching goals:

  • The learners demonstrate they can create an executable script

Schedule:

gantt
  title Lesson plan Command line
  dateFormat X
  axisFormat %s
  Prior knowledge: prior, 0, 5s
  Theory: theory, after prior, 5s
  Exercises: crit, exercise, after theory, 25s
  Feedback: feedback, after exercise, 10s

Why?

Instead of typing commands in the terminal all the time, you can put these in a file. Such a file, called a script, can then be shared.

Procedure

Creating an executable script has two steps:

  • Create a script
  • Allow the script to execute

As an example, we create a script, called do_it.sh:

nano do_it.sh

Why use a .sh file extension?

Using .sh as a file extension a social convention for how a Bash script is called, as (1) sh is short for 'shell', (2) Bash is short for 'Bourne Again Shell'. A 'shell' in this context is a program that allows working with an operating system.

As an example, copy-paste this content into the script:

#!/bin/bash
echo "Hello!"

What does this program do?

The first line is called the shebang, and indicates this is a Bash script.

The second line displays the text between double quotes.

Save and close nano.

  • Use CTRL-O to start saving your file, then edit the filename, then press enter
  • Use CTRL-X to exit

Use chmod to make the file executable:

chmod +x do_it.sh
  • +x can be read as: 'add the right to execute'

Create read-only files

If you want to protect your data from being modified accidentally, chmod can create read-only files, by removing the writing rights using chmod -w.

Exercises

Exercise 1: create an executable script

  • Create a file called do_it.sh using nano
Answer

Use nano to create it:

nano do_it.sh

Then do CTRL + O to save, CTRL + X to exit

  • Edit the file do_it.sh to have the content below:
#!/bin/bash
echo "Hello!"
Answer

Use nano to edit it:

nano do_it.sh

Then do CTRL + O to save, CTRL + X to exit

  • Make the script executable
Answer

Do:

chmod +x ./do_it.sh
  • Run the script
Answer

Run the script:

./do_it.sh

Or, alternatively:

bash do_it.sh