Running your first shell script

We'll break down the components of our first script. If you do not have an editor please refer to the getting started with vim guide below

Our first script

First open your favorite text editor and create file named hello.sh

hello.sh
#!/bin/bash # Every bash script needs to start with a shebang line 
# like the one above this tells the OS what shell to use
echo "Hello World" # The echo command prints to stdout 
# Meaning it'll print whatever follows it to the terminal

Save the file and exit your text editor.

In order to run scripts they need to be executable, this means the permissions of the file need to be change. Every file can have read, write, and execute permissions. By default files are not executable on creation.

The following commands can be copy and pasted but will only work if you are in the directory in which the hello.sh script exists. Utilize the ls command to check if the script is in your current directory and the cd command to change to a new one.

We'll update our file permission to make the file executable:

chmod +x hello.sh
# chmod stands for change mode the +x option adds execute permission
# and our argument is the script we created "hello.sh"

Once the script has been made executable it can be run

./hello.sh
# scripts are run by referring to the file 
# the `./` means from the current directory that is the starting point
# if the hello.sh script is in the current directory it will run
# the output of the script should be "Hello World"

If you do not recieve the expected output double check the directory, and the permissions of the file, the permissions for the file should be as such.

What we're looking for in this case is the x on the left side of the permissions. For more info on permissions refer to the permissions page below.

Last updated