Bash by Example: Hello World
Your first Bash script. This sample code demonstrates the shebang line, the echo command, and how to make a script executable.
Code
#!/bin/bash
# This is a comment
echo "Hello, World!"Explanation
Every Bash script typically starts with a "shebang" (#!) followed by the path to the interpreter. This tells the system which program should execute the script. For Bash, this is usually /bin/bash or /usr/bin/env bash for better portability across different systems.
The echo command is the fundamental way to print output to the terminal (standard output). It automatically adds a newline at the end of the string. You can use double quotes " or single quotes ' for strings, though they behave differently regarding variable expansion.
To run this script, you typically need to make it executable using chmod +x script.sh and then run it with ./script.sh. This security feature prevents accidental execution of text files and ensures that the script runs with the correct permissions.
Code Breakdown
#!/bin/bash is the shebang line. It must be the very first line of the file and instructs the operating system to use the Bash interpreter to execute the script.# indicates a comment. Everything following this character on the same line is ignored by the interpreter, allowing you to document your code.echo prints text to the screen. It is one of the most frequently used commands in Bash scripting for outputting status updates or results."Hello, World!" is the string argument passed to echo. Double quotes allow for variable expansion, although none is used here.
