loader image

How to write and execute a shell script in Linux?

The steps in writing and executing a shell script are,

  1. Open the terminal. Navigate to the directory you wish.
  2. Create a file with .sh extension.
  3. Write shell script using any text editor.
  4. Give the script permission to execute.
  5. Execute the shell script.

Open terminal ( Ctrl + Alt + T ) and navigate to the directory where you want your shell script to be created. The cd command can be used to change the current working directory. The syntax of cd command is,

cd directoryname

To know the current working directory you can use the pwd command.

pwd

It will print the current working directory location in the terminal.

Hello world program

Create a file new file with .sh extension using a text editor. You can use the following command to create a file named myprogram.sh using “nano text editor”.

nano myprogram.sh

Add the following source code. This line of code will print a “Hello world” message on the screen when executing.

echo "Hello World"

Check out Linux Shell Scripts Examples here !

Making the shell script executable

To make the file we created executable, it is necessary to set execute permission of the file using the following command.

chmod +x myprogram.sh

Execute the shell script

To run the shell script, try the following command.

./myprogram.sh

What we have been doing !

how to write and execute a shell script
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top