DEV Community

Ayush Gupta
Ayush Gupta

Posted on

Bash Scripting - Basics

Hi Everyone,

Lets try to work with the Bash Scripting now.

In the previous post we have created only a .sh file and mention the shebang statement as #!/bin/bash which tells us that we are using Bash shell.

Lets try to use the features which Bash Shell may provide to us.

lets create a .sh file once and give it a name hello.sh

but you may be thinking how do we create this .sh file ?

we can use a text editor which is a part of Linix

for example - vi text editor

in our terminal we can type -

vi hello.sh
Enter fullscreen mode Exit fullscreen mode

now vi text editor will be open for us, but we will not be able to add anything as of now, first we need to go into the insert mode, by pressing "i" button in your keyboard, after that it will show us that we are in insert mode and now we can start editing the hello.sh file

as discussed in previous post, first we need to add the shebang statement to tell what shell we are using

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode
  1. Lets create a simple script, that will print "Hello World" when we execute it
#!/bin/bash

echo "Hello World"
Enter fullscreen mode Exit fullscreen mode

as of now we have added above 2 lines , one is shebang statement and second is echo "Hello World"

but we have a roadblock, before executing the hello.sh file, we need to save this hello.sh file and come out from the text editor right ?

in order to do that, we need to do following -

press escape -> press shift + :wq -> press enter

here w - write or save the file, and q - quit

now we are out from the vi text editor

lets see how to run or execute our script now, and regarding this we need to follow the following way of executing the script

./hello.sh
Enter fullscreen mode Exit fullscreen mode

but it may still not work, due to permissions

so we need to change the permissions first using following

chmod +x hello.sh
Enter fullscreen mode Exit fullscreen mode

here we are just giving executable permission to our hello.sh file to user, group and others, means everyone can execute our hello.sh file or script

now lets follow same -

./hello.sh
Enter fullscreen mode Exit fullscreen mode

we will get -

Hello World

Top comments (0)