How to Run a Bash Script

Running a bash script is easy, but it does take a few steps and it’s important to do them in the right order. In this post, we’ll go through the steps to ensure that your script will run correctly 😉

The first step is to make a bash script. Any bash script uses the Linux commands. A script can simply be a file with a list of commands and the .sh extension. If you are new to Linux, you can use this site to practice.

The second step is to make sure that your script file is executable. In Linux and macOS, you can check if a file is executable by running the ls -l command and then looking for an x in the permissions column.

The example below shows the difference:

$ ls -l *.sh
-rwxrwxr-x 1 frank frank   43 mei 29 16:30 hello.sh
-rw-rw-r-- 1 frank frank 8192 jul  1 19:41 not-executable.sh

If it isn’t executable, run the following command in Terminal.

chmod +x script.sh

To start a script you write:

./script.sh

When to use Bash scripts? 😁

I can write a shell script when I need to, but then continue working in Python or Perl or C++ or whatever real programming language I'm most comfortable with at the time (these days mostly C++).

For example, one of my recent side projects involved crunching data from a database, working with various embedded systems and more. Shell is not the right tool for that kind of application.

Bash is more suited for when you write a lot of commands in the shell anyway and want to automate that.

24