Linux Shell Scripting – Creation and Execution

First Shell Script

Create a file called helloworld.sh (sh is the extension used for shell scripts)

#!/bin/bash
# Hello World Shell script Written for demonstration
echo 'Hello World!'

First Line in the above script is to inform Linux that this file will be executed by bash shell. This line is referred as shebang

In shell scripts any thing written following # is considered as comment

Third line runs a command echo with parameter ‘Hello World!’

Executing scripts

Lets try certain scenarios

  1. execute the following command
hello.sh

output:
-bash: helloworld.sh: command not found

Explanation: * The reason for the above problem is whenever any command is executed, linux tries to find the command or the executable only in the specific directories. * These directories are defined in the Environment Variable PATH * Execute the following command echo $PATH. If you examine the result the file helloworld.sh is not present in any of the directories * One possible solution could be to move helloworld.sh to any of the directories or add the directory of helloworld.sh to PATH variable.

  1. Even after you do the above mentioned resolution and try to run the command helloworld.sh the error Permission denied will occur. To solve this change file permissions by executing the following command
chmod 0755 helloworld.sh
helloworld.sh

########Output###########
Hello World!

Exit Codes

  • Every script executed will return exit codes. The following are the exit codes and their meanings
Exit Code Purpose
0 SUCCESS
1 Error
2 Misue of shell builtins
126 Command invoked cannot execute
127 Command not found
128+n Fatal error signal ā€œnā€
130 Script terminated by Control-C
255 Exit status out of range
  • Exit status can be checked by executing a command
echo $?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner