Bash Hello World Example
Bash is a shell used on Unix-like operating systems. Before starting with your first script, you must know about shebang character.
What is Shebang (#!)
Shebang is declared at first line of any scripts start with “#!” symbols. This tells the shell to which interpreter will be used to run this script if not defined on the command line.
To read more about shebang visit here.
Write Hello World Program
Now create a new file and edit in text editor. You can use any command line text editor of your choice.
$ vim hello_world.sh
add below content to file and save it.
#!/bin/bash echo "Hello World"
Now execute the above-created script. You can execute the script in various ways as follows. Read below methods which are correct and which is wrong.
$ sh hello_world.sh ## Wrong method $ ./hello_world.sh ## Correct method $ bash hello_world.sh ## Correct method
The first way is wrong because you are asking shell to use the sh interpreter (not bash).
The second is right because executing the script without proving any shell information. Now the script will use shell defined with Shebang (#!/bin/bash) interpreter.
The third will also use bash as interpreter, so that fine for our script.
Let’s execute the script without any shell. Simple type script name as follows.
$ ./hello_world.sh -bash: ./hello_world.sh: Permission denied
Oops, what happened now? Not to worry, this error occurred due to permission. Your script doesn’t have to execute permission. So use below commands to set execute permission on the script and then run.
$ chmod +x ./hello_world.sh $ ./hello_world.sh Hello World