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!
Contents
Steps
- 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.
- 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".
- 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. - At the top type the following code
#!/bin/bash
. This is known as a Shebang line. - 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.
- 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
- 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.
- Type ./ListDir.sh to run this script. You should get the list of directories and the message as shown in the above image.
- 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