Hello World in Bash

Hello World in Bash

Hello World in Bash

The "Hello World" program is a simple example often used to demonstrate the basics of a programming or scripting language. In Bash, creating a "Hello World" script is easy and an excellent way to start learning shell scripting.

Steps to Create and Run a Hello World Script

1. Open Your Terminal

The terminal is where you will write, save, and execute your Bash script.

2. Create a New Script File

You can create a new file using any text editor or directly from the terminal.

Command:

nano hello_world.sh

This will open the Nano editor where you can write your script.

3. Write the Script

Add the following lines to the file:

#!/bin/bash # This is a simple Hello World script echo "Hello, World!"

4. Save and Exit

  • In Nano: Press Ctrl+O, then press Enter to save.
  • Press Ctrl+X to exit the editor.

5. Make the Script Executable

Before running the script, you need to make it executable.

Command:

chmod +x hello_world.sh

6. Run the Script

Execute the script by typing:

Command:

./hello_world.sh

Output:

Hello, World!

Understanding the Script

  1. #!/bin/bash:

    • This is the shebang line. It tells the system to use the Bash shell to interpret the script.
  2. # This is a simple Hello World script:

    • This is a comment. It explains the purpose of the script and is ignored by the interpreter.
  3. echo "Hello, World!":

    • The echo command prints text to the terminal.

Run Without chmod +x

If you don't want to make the script executable, you can run it using Bash directly:

Command:

bash hello_world.sh

Output:

Hello, World!

Using Variables in Hello World

You can customize the script by using variables.

Script:

#!/bin/bash # Hello World with a variable message="Hello, World!" echo $message

Output:

Hello, World!

Adding User Interaction

Enhance the script to interact with the user:

Script:

#!/bin/bash # Personalized Hello World script echo "What is your name?" read name echo "Hello, $name! Welcome to Bash scripting!"

Output:

What is your name? Alice Hello, Alice! Welcome to Bash scripting!

Conclusion

Creating a "Hello World" script is a foundational step in learning Bash scripting. From here, you can explore more complex scripts involving loops, conditionals, and functions.

Let me know if you’d like a guide on more advanced Bash topics!

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close