Step 1: Create a ``Hello World`` Script ======================================= .. include:: urls.rst .. contents:: Table of Contents **Objective**: Create a basic shell script that you can executable. **Resources** * |Linux Tutorial| * |Linux file permissions| * |Shell Scripting Tutorial| * |Ryan's Bash Scripting Tutorial| 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. .. code-block:: bash 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: .. code-block:: bash :caption: bash shebang #!/bin/bash .. code-block:: bash :caption: 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. .. code-block:: bash ./my-file.sh * ``application my-file`` can be used to directly execute the file using the specified application. Examples are: .. code-block:: bash 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). .. code-block:: bash root@vps298933:~# echo "Hello world!" Hello world! root@vps298933:~# .. code-block:: bash 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**. .. code-block:: bash #!/bin/bash 3. Add an ``echo`` statement. .. code-block:: bash echo "Hello world!" 4. Set the executable flag. .. code-block:: bash chmod +x my-file.sh 5. Run the script. .. code-block:: bash ./my-file.sh 6. Execute the script using ``bash``. Expected output ^^^^^^^^^^^^^^^^ .. code-block:: bash 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:~#