Step 1: Create a Hello World Script

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 permission

    • w : Write permission

    • x : 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 use bash or sh. 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 use sh 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 using

      the 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

  1. Create and edit a file.

  2. Add the bash shebang to the first line.

#!/bin/bash
  1. Add an echo statement.

echo "Hello world!"
  1. Set the executable flag.

chmod +x my-file.sh
  1. Run the script.

./my-file.sh
  1. 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:~#