Menu
Coddy logo textTech

Create And Run A Script

Part of the Fundamentals section of Coddy's Terminal journey — lesson 67 of 82.

Now that you understand what a shell script is, let's create one and run it. The process involves three steps: creating the file, making it executable, and running it.

First, create a new file with a .sh extension. You can use echo with redirection to write the shebang and commands:

echo '#!/bin/bash' > greet.sh
echo 'echo "Hello, World!"' >> greet.sh

Before you can run the script, you need to give it execute permission. By default, new files don't have this permission. Use chmod to add it:

chmod +x greet.sh

Now you can run the script by specifying its path. For a script in your current directory, use ./ before the filename:

./greet.sh

This outputs Hello, World!. The ./ tells the shell to look in the current directory rather than searching the PATH. Without it, the shell won't find your script.

You can also run a script without execute permission by calling the interpreter directly:

bash greet.sh

This explicitly tells Bash to interpret the file, bypassing the need for execute permission.

challenge icon

Challenge

Easy

Create a shell script called welcome.sh that prints Welcome to scripting! when executed.

Follow these steps:

  1. Create the script file with the shebang line (#!/bin/bash)
  2. Add an echo command that prints the welcome message
  3. Make the script executable using chmod
  4. Run the script using ./

Your output should be:

Welcome to scripting!

Hint: Use echo '#!/bin/bash' > welcome.sh to create the file with the shebang, then echo 'echo "Welcome to scripting!"' >> welcome.sh to add the command. Make it executable with chmod +x welcome.sh, then run it with ./welcome.sh

Cheat sheet

To create and run a shell script, follow these three steps:

1. Create the script file

Create a file with a .sh extension and add the shebang line and commands:

echo '#!/bin/bash' > script.sh
echo 'echo "Hello, World!"' >> script.sh

2. Make it executable

Use chmod +x to add execute permission:

chmod +x script.sh

3. Run the script

Execute the script using ./ to specify the current directory:

./script.sh

Alternatively, you can run a script without execute permission by calling the interpreter directly:

bash script.sh

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals