Jarkko's guides
You are here: Home » Linux » Scripting

Scripting

Shebang

You can use the first line in a script to specify what should be used to run it (a shell or interpreter). The line needs to start with #! (colloquially called shebang) and then the path to the shell/interpreter. Example for a Bash script:

#!/bin/bash
echo Hello

The script must additionally be made executable with chmod +x my_script. Then it can be run with:

./my_script

Without the shebang line you would need to run it like this:

bash my_script

For best compatibility with everyone's system this shebang line can be used instead of pointing to an absolute path. The env program looks up where the shell/interpreter can be found (in which directory that is in the PATH variable), so that it doesn't matter where it is located on the system.

#!/usr/bin/env python3

Shell scripts

Shell scripts can be as simple as a list of commands you would otherwise manually type on the command line. If your script mainly needs to run other programs/commands, then a shell script is the way to go. The Bash shell also supports typical scripting things like “if” and loops.

Put your shell scripts in directory ~/bin and add that directory to the PATH variable. You can do that with this extra line in ~/.bashrc: export PATH=$PATH:~/bin

Then you can execute them by simply typing their name, no matter what directory you are in. Remember that the scripts should be made executable.

Very handy for error handling is to include the line set -e in your shell script. Any subsequent command in the script that quits with an error will cause the script to stop.

Useful scripting languages

Two good scripting languages to highlight are Perl and Python:

  • Perl excels at textual manipulation. You can use regular expressions to find, remember and replace certain patterns.
  • Python is a good general-purpose scripting language. Whatever you want to create, it is likely possible with Python. There are loads of third-party libraries available to do various things.
Previous Next

ALL THE TOPICS ON THIS WEBSITE:

Linux

Raspberry Pi

Digital room correction

Web design

By Jarkko Huijts
Jarkko's guides

Table of Contents

Table of Contents

  • Scripting
    • Shebang
    • Shell scripts
    • Useful scripting languages

LINUX

  • Intro
  • History
  • Open source
  • Distributions
  • Command line
  • Tool help
  • Remote access
  • Directory hierarchy
  • Basic commands
  • Viewing & editing files
  • Processes
  • GNU & other utilities
  • Users & permissions
  • Partitions & mounting
  • System administration
  • Software packages
  • Desktop environments
  • Scripting
  • Audio

AVAILABLE TOPICS

  • Linux
  • Raspberry Pi
  • Digital room correction
  • Web design