Code Done Right!

Running script

If you have a task that you are performing with any regularity, then you can write a script which will do that for you. The only question is how to do it. I encourage you to grab a book on working with CLI, like this one for example – The Linux Command Line, 2nd Edition: A Complete Introduction. But for now I expect you will be grabbing script from GitHub or other RaspberryPi related sites and wondering how to make it work.

Creating script file

In order to create a script file, create a new file with .sh extension, e.g. example_script.sh

nano example_script.sh

Each script file needs to start with a shebang#! after which you specify the shell that will execute the script. Default shell for RaspberryOS and Debian-based distributions is Bash.

#!/bin/bash

In order to execute the script the file needs execute permissions. Run the following

sudo chmod +x example_script.sh

Example script file

#!/bin/bash

echo "Hello world!"

This is a rudimentary script that will display the well-known “Hello world!” message in your terminal window.

Running script

In order to execute a script file named example_script.sh you just have to type the name prefixing it with ./ like so

./example_script.sh

But you have to be in the same directory where the script is located.

If you are in a different directory, instead of prefixing the name with ./ use the full path to your script, like so

/path/to/script/example_script.sh

After you press ENTER, the script will be executed.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.