Step 1: Create a Hello World
Script
Table of Contents
Objective: Create a basic shell script that you can executable.
Resources
The Basics
Most shell scripts use extension
.sh
. The extension is not required, but it helps to identify the file.Attributes are used to set Linux file permissions, which are:
r
: Read permissionw
: Write permissionx
: Execute permission–
: No permission set
The
chmod
command is used for changing the permissions.You can make the file executable by setting the
x
flag.
chmod +x my-file.sh
The shebang
#!
is the first part of the script. It tells the OS which program should run the script. We will usebash
orsh
. Therefore, all of our scripts will start with one of these two:bash shebang#!/bin/bash
sh shebang#!/bin/sh
Bash stands for Bourne Again SHell, and is a replacement/improvement of the original Bourne shell (sh).
Note: Not all systems use
bash
. Some will usesh
instead.
There are two ways to execute a file in Linux:
./
is used if both the executable flag and shebang are set../my-file.sh
application my-file
can be used to directly execute the file usingthe specified application. Examples are:
bash my-file.sh python index.py
The
echo
command echos or sends the text to the terminal or to another file using standard output (stdout).root@vps298933:~# echo "Hello world!" Hello world! root@vps298933:~#
root@vps298933:~# echo "Hello world!" > my-file.txt root@vps298933:~# cat my-file.txt Hello world! root@vps298933:~#
Your First Script
Create and edit a file.
Add the
bash
shebang to the first line.
#!/bin/bash
Add an
echo
statement.
echo "Hello world!"
Set the executable flag.
chmod +x my-file.sh
Run the script.
./my-file.sh
Execute the script using
bash
.
Expected output
root@vps298933:~# nano my-file.sh
root@vps298933:~# chmod +x my-file.sh
root@vps298933:~# ./my-file.sh
Hello world!
root@vps298933:~#
root@vps298933:~# bash my-file.sh
Hello world!
root@vps298933:~#