How to Write in Shell Script
Learning the command line in Linux is always the first step for a new Linux user. If you want to start doing more, such as automating tasks in Linux, writing a shell script is the next step. Your first shell script doesn't have to be overly complex, and you can employ the same commands you use at the command line, with a few extra lines to make it a full script. In no time at all, you'll be writing complex scripts that perform a variety of functions.
Instructions
-
-
1
Open the command line interface, then open your preferred text editor. The most common text editor is vi, but nano and Emacs are popular as well. If you want to name it, enter the command "vi new_script."
-
2
Write "#!/bin/bash" as your first line. This tells the interpreter that this script uses bash. Write the comment "#My new script" on the next line. The "#" tells the interpreter to ignore this line because it's a comment. Use comments to tell you what a script does. In multi-line scripts, comments can describe what tasks different parts of the script perform.
-
-
3
Create your first action. Start with a simple action: "echo "hello world"" (without the outside quotes). This tells the command line to print "hello world" when you run the script.
-
4
Save the script and exit the text editor. Make sure the correct permissions are set on the script file. The command "chmod 755 new_script" gives you read and write access to the file.
-
5
Check that the script file is in your path. Check your path first by typing "echo $PATH" into the command line. This shows you what folders are in your path. If you don't see the directory your script is saved to in the path, type the command: "export PATH = $PATH my_folder" to add the directory. Replace "my_folder" with the directory you want to add.
-
6
Test your script. If you have added the script's directory to your path, run it by typing "./new_script" at the command line. If you have not added the script's directory to your path, you can still browse to the directory using "cd" and run "./new_script" (if everything in the script is correct, you should see the command line print "hello world"). The command line will then return to your regular prompt.
-
7
Write a new script. Use it to delete files, or move them to a new location. Pass arguments to a script with "$*"--such as "mv $* downloads" which moves a file passed from the command line to a folder called Downloads. As you become more familiar with the command line, you will find more and more simple tasks that you'll want to automate with a script.
-
1
Tips & Warnings
Anything you do in a script will immediately affect your computer. Take caution with commands such as "rm" which deletes files.
References
Resources
- Photo Credit keyboard image by red2000 from Fotolia.com