A “Hello, World!” bash shell script is a bash program that outputs “Hello, World!” to a user. This script illustrates the basic syntax of a bash shell scripting language for a working program. It is your very first program when you are new to a bash shell scripting.
How to write hello world bash shell script
The procedure is as follows:
- Create a new file called hello.sh using a text editor such as nano or vi:
- Add the following code:
echo "Hello World"
- Set the script executable permission by running chmod command:
chmod +x hello.sh
- Run or execute the script using following syntax:
Improving Hello World script
Let us create a program called update-hello.sh as follows:
#!/bin/bash # Usage: Hello World Bash Shell Script Using Variables # Author: Vivek Gite # ------------------------------------------------- # Define bash shell variable called var # Avoid spaces around the assignment operator (=) var="Hello World" # print it echo "$var" # Another way of printing it printf "%s\n" "$var"
Run it as follows:
chmod +x update-hello.sh
- First line of the script (#!/bin/bash) is shebang. It tells the Linux/Unix how to run the script.
- Each shell comments start with #.
- Declaring a variable: Variable_Name="Values_here".
Next create a program named hello2.sh to display current date and computer name as follows:
#!/bin/bash var="Hello World" # Run date and hostname command and store output to shell variables now="$(date)" computer_name="$(hostname)" # # print it or use the variable # Variable names are case sensitive $now and $NOW are different names # echo "$var" echo "Current date and time : $now" echo "Computer name : $computer_name"
Run it as follows:
chmod +x hello2.sh
Reading a value from input
Our final hello world program reads input from the keyboard using the read command. Create a bash shell script named hello-input.sh:
$ nano hello-input.sh
Append the following code:
#!/bin/bash # Clear the screen clear # Read input using read command read -p "May I know your name please? " name echo "Hello $name, let us be friends" echo ""