So you’ve either recently come to the Unix world or you are finally getting around to some shell scripting to ease your daily operations (Say hi Jim!). So for starters what *IS* bash scripting? Scripting in general is making a program or “script” do all or most of your work for you. For instance if you wanted to find every instance of the word “hosting” in a particular file that is 30,000 lines long. That would take a LONG time doing that by hand and you would likely miss several along the way (being a fallible human and all). So instead we would use a grep (or similiar command) from the command line.
Well that may be easy enough for just one command but what if we then need to check all of those lines that are found and seperate them by date or some other criteria, then sort them out etc? For this we will use scripting. We can also use scripting for events that we want to take place every single day, whether it be simple or complex. This can be done via a cronjob, but we can get to that in a later article. So first off we’ll need to find where our “bash” resides…
which bash > helloWorld.sh
“which bash” will give us the location of the bash that is being used within our path. The > will send that result into a new file titled “helloWorld.sh” that we will use for our script. Now if we open up that file we will have something like the following:
/usr/bin/bash
Nothing else should be in our file at this point. This is good but not quite what we need. We need to add #! in front of this. This tells our script that we will be using /usr/bin/bash as our shell to run the rest of this script.
#!/usr/bin/bash
To complete our very first script all we’ll need to do is enter in the following a few lines (doesn’t matter how many) after our #!/usr/bin/bash line, like so:
#!/usr/bin/bash echo "Hello World!"
Now we have our script ready, we just need to execute it. There are two ways to accomplish this, first we can simply chmod the file to give it the execute (x) permission. For simplicity sake we’ll say its:
chmod 755 helloWorld.sh
The 7 sets it so that the owner (you) can do anything with the file, the first 5 sets it so that anyone in its group can read and execute it and likewise for the last 5 but for this is for everyone, not just the group. More on chmod and chown in future articles.
Now that we have our file chmod’d to be executable we can run it right from where we are by typing
./helloWorld.sh
and our output should be simply:
Hello World!
As mentioned there are two ways to execute the file. For the second method we could type the following and not have to worry about permissions (only ownership — but since we own it we really don’t have to worry about that either).
/usr/bin/bash ./helloWorld.sh
And, again, our output would be the same:
Hello World!
Congratulations, you’ve just made your first Bourne Again Shell (Bash) Script.