Thứ Ba, Tháng Hai 11, 2025
spot_img
HomeTechnologyHow to create and run shell scripts in Ubuntu 22.04

How to create and run shell scripts in Ubuntu 22.04

A script is used in Linux and commands are written into it according to job and task characteristics. When executing such a script, each command in it will be executed one by one in order. Shell is a user-written command interpreter. Script shell helps users write and execute multiple commands at the same time.

In this article, readers will learn how to execute shell scripts through command line input. This article is using Ubuntu 22.04 and Ubuntu 20.04. Before demonstrating how to execute a shell script via CLI, let's first look at how to create a shell script.

Prerequisites

  • Ubuntu system, any recent version will work.
  • The user has sudo privileges

Create a file with the extension “.sh”

To create a “.sh” file, follow these steps:

1. Open the default editor via the menu bar

You can use the default text editor in Ubuntu or if there is any other editor installed in your system such as vim editor. This particular tutorial is using the default text editor.

Enter “editor” and click “Text Editor”.

Open the editor
Open the editor

The default editor will be opened.

Ubuntu desktop editor
Ubuntu desktop editor

2. Write the command in an untitled document and save it with “.sh” extension

You can write any command according to job requirements or assigned tasks. This particular article is writing the following echo commands/code in an untitled document.

echo "Hello World"
echo "Ubuntu 20.04 LTS tutorial"
echo "Today’s task"
Test script
Test script

Now, save the file with the extension “.sh” into the folder of your choice. This example saves it to the default directory – the home directory – and the file is named “tutorial.sh”.

Xem thêm  Instructions for turning off File Explorer thumbnails in Windows 11
Save the test script
Save the test script

Now the “tutorial.sh” script will look like this in the text editor after being saved.

Shell script
Shell script

3. Execute shell script “guide.sh” via CLI

You must execute the shell script via command line input.

You must first make the shell script executable by running the following command:

$ chmod +x scriptname

Write your shell script name instead “scriptname” in the command above. For this particular tutorial, the script name is “tutorial.sh”.

Make the shell script executable
Make the shell script executable

Run the script with the following command:

$ ./scriptname

The script name is “tutorial.sh” as mentioned above.

Execute shell script
Execute shell script

When you run the above command, it will execute the script line by line and display the following output:

Test script results
Test script results

See more:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments