Home Linux How to write a shell script and run it

How to write a shell script and run it

by Anup Maurya
11 minutes read
How to write a shell script and run it

In this tutorial, we will go through the steps to write a shell script and run it on a Linux-based operating system.

A shell script is a computer program designed to be executed by the Unix shell, which is a command-line interpreter used in Unix-based operating systems such as Linux and macOS. Shell scripts are commonly used to automate repetitive tasks, configure system settings, and perform various administrative tasks.

Writing a shell script

  • Open a text editor such as Nano or Vim on your Linux terminal. You can use any text editor of your choice.
  • Start your script with a “shebang” line. This line tells the shell which interpreter to use for running the script.

For example, the shebang line for the bash interpreter would be

#!/bin/bash
  • Write your script commands below the shebang line.

For example, the following script simply prints “Hello, World!” to the terminal

#!/bin/bash 
echo "Hello, World!"
  • Save the script with a descriptive filename and a “.sh” extension.

For example, you can save the above script as “helloworld.sh”.

Running a shell script

  • Open a terminal window and navigate to the directory where your script is saved.
  • Type “ls” to list the files in the directory and make sure your script is there.
  • Make the script executable by using the “chmod” command.

For example,

chmod +x helloworld.sh
  • Run the script by typing its filename preceded by “./”.

For example,

./helloworld.sh 

This should output “Hello, World!” to the terminal.

Congratulations! You have successfully written and executed your first shell script.

Tips and best practices

  • Always start your script with a shebang line specifying the interpreter to use.
  • Use descriptive filenames for your scripts to make them easy to identify and remember.
  • Keep your scripts organized and easy to read by using comments and whitespace.
  • Test your scripts thoroughly before using them in a production environment.
  • Keep in mind that shell scripts can be very powerful and potentially dangerous. Be careful not to accidentally delete or modify important system files.

related posts

Leave a Comment

Enable Notifications OK No thanks