Write a Shell Script Using Bash Shell in Ubuntu

Ever wanted to Automate operations in your OS? Ever wanted to write a program that could create a file and copy that file to a directory? Ever wanted to do all this using the Famous BASH Shell in Ubuntu? If the answers to these three questions are "Yes", then this is the How-To for you!

Steps

  1. Launch the Terminal. You can launch the terminal by opening the dash and searching for it by name. You could also open it by using the keyboard shortcut Ctrl + Alt + T.
  2. In the Terminal launch the vi/vim editor. Vim is a free and popular text editor that uses the command line interface. To install Vim, type "sudo apt-get install vim".
  3. In the terminal window, type vim ListDir.sh and hit enter. Once inside the Editor, type "I" or "i". This will allow you to insert / start typing your shell script.
  4. At the top type the following code #!/bin/bash. This is known as a Shebang line.
  5. Type the code as shown in the figure.
    • The first line (echo "Welcome") prints the line "Welcome" into the terminal. echo is used to return the given text and a new line.
    • The second line (ls) lists the contents of the directory. ls is short for list.
    • The final line (another echo statement) returns the text This completes the list of directories.
  6. Type the following key combinations, Esc + : + wq to escape the editor. This will write the changes to the file and bring you back to the terminal. Save the file as ListDir.sh
  7. Enter the following command: chmod +x ListDir.sh
    • chmod is a command used in Unix like operating systems to change the access permissions to a file.
  8. Type ./ListDir.sh to run this script. You should get the list of directories and the message as shown in the above image.
  9. Congratulations on writing your 1st Shell Script using Bash in Ubuntu Linux!

Tips

  • By default, vim is not installed.
  • Use vim <yourfile.sh> to edit your shell scripts.
  • Enter your password and let Ubuntu do the magic.
  • After the install is completed, issue the command.

Warnings

  • For starters, place your shell scripts in your home directory as you begin your shell script journey. Once comfortable, place them in your required directory system.
  • Ensure that the files you create, do not reside in any system directories of the / = root file system

Related Articles