Wednesday, April 2, 2008

The Noobs Guide to Bash-Scripting - Part 1

So let's say that you want to perform tedious file management tasks but you don't want to take the time out to program something in a real language (C,C++). A bash script is the right thing for you!


Enough talking, lets get started! As always, file structure in your projects is crucial to ensure that you don't accidentally delete something. So lets create a folder called "bash" inside your home directory, this will be where all your bash scripts are kept. Then create a folder called "helloworld" inside your bash folder. Now create a file called "hello_world" inside your "helloworld" folder.

You should end up with a folder structure like this:

---- bash
-------- helloworld
------------ hello_world

Now, open up hello_world with your favorite text editor. I suggest gedit, but there are many (vim, nano, etc...). On most Linux systems, the first line of your bash script should be:

This is location of your bash program. Nothing complicated, just make sure it's the first line.

The Basics

The rest of the bash script consists of commands that you would normally be able to type in a command line.

eg. Typing ls in command line will get the same results as running a bash script that contained:

The commands in a bash script will be run in the directory that you run the script in. So if you run the above script in /home/user , then the script would print the contents of /home/user in your command line.

Back to our hello_world script; we want this script to output a message onto the screen. One suitable command for this is echo. The usage of echo is pretty simple:
echo "Your message here"
So, lets implement this in our hello_world script. Here is the final script:
echo "Hello World!"
For more options on how to use echo, check out it's man page:
man echo

Finishing Up: Running the script

Almost there! Now all we need to is make sure the hello_world file is executable. We can do this with one command while in the helloworld directory.
chmod +x hello_world
Then it's a simple matter of running the script:
Alternatively, you can run the script without having to chmod it:
sh hello_world

Hopefully our script ran successfully, if not, go back and check that your code is correct.

Alright, now that our script is fully functional, we want to be able to run it without having to go into the .../bash/helloworld/ directory. This is relatively simple, all you need to do is copy your script into the /usr/local/bin directory. On most systems, you will need root access.

Once you've copied the script, then just have to enter hello_world into your command line to run the script.

This concludes the first part of The Noobs Guide to Bash-Scripting, there will be more interesting things coming in the next part, such as conditional statements, functions and arguments. So be sure to come back soon, until then, play around with your script!

No comments: