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

Hi there šŸ‘‹, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
šŸ‘Æ I’m looking to collaborate on open-source PHP & JavaScript projects
šŸ’¬ Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close