How to Write a Bash Script in UNIX
Bash is one of the shell environments in Unix and Linux. A Bash script is a way to write small programs (i.e., scripts) that perform regular system tasks. It can also request user input, handle arguments and perform many of the other takes done by more robust scripting languages such as Perl. Here's how to write a very simple Bash script.
Instructions
-
The Steps
-
1
Check where the Bash interpreter is located on your system with the command "Which bash" (no quote marks). It will return a location such as /bin/bash.
-
2
Open any text editor, and in the first line, type "#!/bin/bash" (no quote marks). This line must be in the very first line of any Bash script. Without it, the script will not run. The #! combination is called a Shebang.
-
-
3
Enter commands in the next few lines. For example, the following script moves the contents of a directory into a new directory and tells you when it is finished.
#!/bin/bash
mkdir /home/kristen/newDoc
mv /home/kristen/Documents/* /home/kristen/newDoc
echo "Done!"
Notice that the commands are the same in Bash as they are from the command line. -
4
Save your file and make it executable with the following command: "chmod +x" (no quote marks).
-
5
Execute the script from the command line: "./sample.sh" (no quote marks).
If you are not in the same directory as the script, you will have to specify the complete path to the script: "./home/user/scripts/sample.sh" (no quote marks).
-
1
Tips & Warnings
Bash can do more than just handle simple commands. Please check the References section for more information.
References
Comments
-
jmboulos
Apr 20, 2010
Beware of capitalization in Linux. For step 1, the "Which bash" most likely will not work because "which" is a system command and needs to be lowercase "w" to be recognized as such.