Android,iOS,Gadgets,Reviews Everything About Technology

Linux Bash Script Step By Step Guide , You Will Love It

27,967

Today we are going to talk about bash scripting or shell scripting and how to write your first bash script. Actually, they are called shell scripts in general, but we are going to call them bash scripts because we are going to use bash among the other Linux shells.

There are zsh, tcsh, ksh and other shells.

In the previous posts, we saw how to use the bash shell and how to use Linux commands.

- Advertisement -

The concept of a bash script is to run a series of Commands to get your job done.

To run multiple commands in a single step from the shell, you can type them on one line and separate them with semicolons.

pwd ; whoami

Actually, this is a bash script!!

The pwd command runs first, displaying the current working directory then the whoami command runs to show the currently logged in users.

You can run multiple commands as much as you wish, but with a limit. You can determine your max args using this command.

 getconf ARG_MAX

Well, What about putting the commands into a file, and when we need to run these commands we run that file only. This is called a bash script.

First, make a new file using the touch command. At the beginning of any bash script, we should define which shell we will use because there are many shells on Linux, bash shell is one of them.

Bash Script Shebang

The first line you type when writing a bash script is the (#!) followed by the shell you will use.

#! <=== this sign is called shebang.

#!/bin/bash

If you use the pound sign (#) in front of any line in your bash script, this line will be commented which means it will not be processed, but, the above line is a special case . This line defines what shell we will use, which is bash shell in our case.

The shell commands are entered one per line like this:

You can type multiple commands on the same line but you must separate them with semicolons, but it is preferable to write commands on separate lines, this will make it simpler to read later.

Set Script Permission

After writing your bash script, save the file.

Now, set that file to be executable, otherwise, it will give you permissions denied. You can review how to set permissions using chmod command.

chmod +x ./myscript

Then try run it by just typing it in the shell:

./myscript

And Yes, it is executed.

Print Messages

As we know from other posts, printing text is done by echo command.

Edit our file and type this:

Comments