Scripting Hello World
Writing a Hello World program is a rite of passage in programming. Here’s how to do it in a shell script — straight from the command line on an enterprise Linux system.
Prerequisites
This guide assumes you're comfortable with
vim
. If not, maybe start
there first.
Step-by-Step Guide
-
Create the script file
Starting from a shell, create and open a new file, "HelloWorld.sh", using
vim
: -
Write the script
Inside "HelloWorld.sh", enter Insert mode and type this exactly:
- The first line (
#!/bin/bash
) is called a shebang. It tells Linux which interpreter should run the script. In this case, it's the Bash shell. - The blank line is optional, but it makes the script easier to read.
- The next line with the keyword
echo
just prints Hello World! to the screen.
- The first line (
-
Save and exit
Go back to Normal mode, save the file, and exit using
:wq
-
Make the file executable
By default, new files aren't executable. Add that permission:
- Using
700
gives the owner full permissions (read, write, execute) while removing all permissions for group and others. See Basic Permissions for a more thorough explanation.
- Using
-
Run the script
Finally, run it:
Troubleshooting
If your script didn’t run the first time, don’t worry — here are the common gotchas:
Permission denied when running ./HelloWorld.sh
-
You probably forgot to make it executable. Run:
command not found
or nothing happens
- Make sure you're running it with
./HelloWorld.sh
and not justHelloWorld.sh
. The./
tells the shell to look in the current directory for the script.
Weird characters in the output
- Make sure you typed the script exactly as shown, especially the quotes around "Hello World!".
- Double-check that the first line is
#!/bin/bash
with no extra spaces or characters. If you leave out the!
, for example, it won't work.
Using Windows line endings
-
If you created the script on Windows and then copied it to Linux, it may have Windows-style line endings (CRLF) instead of Unix-style (LF). This can cause issues. To fix it, run:
Still stuck?
-
Try running the script with
bash -x
to see what’s going on behind the scenes: