DEV Community

Twinkle lahariya
Twinkle lahariya

Posted on

Shell Scripting Basics

What is a Script?

A Script is a command line program that contains a series of instructions.
Anything that you can type in a command line, you can put in a script.

Let's greet the world with a script.

#!/bin/bash echo "Hello World"

we will look into every component of this script a bit, but before that, let's first see how a script is interpreted and executed.

Interpreting a Script.

Any script is interpreted by an interpreter that executes the command one after the other. In the case of shell script, the shell accesses the interpreter and executes the commands. Functions that shell scripts support include loops, variables, if/then/else statements, arrays and shortcuts.

Now the question is, why do we need scripts?

If you find yourself doing a set of tasks over and over again, you might want to automate that task. Scripting is a great way to automate tasks.

Components of a Script

echo "Hello World"
Enter fullscreen mode Exit fullscreen mode

A script starts with
#! : Shebang, which represents the beginning of the script followed by the path of the interpreter.
/bin/bash : This is the path to the interpreter used to execute commands written in the script.
Here are some more examples of shell scripts, each using a different shell program as the interpreter:
#!/bin/zsh : This script uses zsh as the interpreter. #!/bin/csh : This script uses csh as the interpreter. #!/usr/bin/python : This script uses python as the interpreter.

Is the Shebang mandatory?

No, the shebang is an optional command. If we do not specify shebang, then the script runs in the current shell.

Is this a problem?
No, if you are lucky.
Different shells have slightly different syntax. It's safe to be explicit and specify the exact interpreter to be used with the script.

After, the first line of the script follows the executable instructions. In our case, it is:
echo "Hello World" : Displays hello would to the console.

Now, save the file with the .sh extension in the location that the shell can access.

Run a shell script

  1. Make the script executable with command chmod +X <fileName>
  2. Run the script using ./<fileName>

In order to run our HelloWorld program:

  1. save the file with
  2. run the command chmod +X
  3. execute the script ./

output :

> ./
Hello World
Enter fullscreen mode Exit fullscreen mode

What happens when we execute a script?

When we execute a script that has a shebang, what happens it that the interpreter executes and the path used to call the script is passed as an argument to the interpreter.
And then every command following the Shebang gets executed line by line.

Voila! We just ran our first shell script.

Up next is variables and tests in a shell script..

Until next time, love ❤️

Top comments (0)