Writing a Simple Hello World Bash Script
Writing a Simple Hello World Bash Script
In this post let us learn how to write a simple bash script. We will use vim editor to write the script. The script prints the “Hello World” message on the console.
Steps to create a Bash Script
Lets us name the script myscript.sh
Open the command shell and type the following.
# vi myscript.sh
To enter edit mode type the key i
Enter the script code as shown below:
#!/bin/bash echo "Hello World \n"
Type :wq<Enter> to save and quit the vi editor screen.
Now you need to provide execute permission to the script so that you can execute the script.
# chmod +x myscript.sh
Execute the script.
#./myscript.sh
That’s it. You have successfully executed a simple bash script. Successful script run would print Hello World message on the console screen.
A common problem while editing files with vim editor is that you may encounter the following error.
Found a swap file by the name “.myscript.sh.swp”
While opening file “myscript.sh”
(1) Another program may be editing the same file. If this is the case,
be careful not to end up with two different instances of the same
file when making changes. Quit, or continue with caution.
(2) An edit session for this file crashed.
If this is the case, use “:recover” or “vim -r myscript.sh”
to recover the changes (see “:help recovery”).
If you did this already, delete the swap file “.myscript.sh.swp”
to avoid this message.
Simply follow the instruction to recover the previous changes or Enter to discard the changes.