Command Line Magic: Scripting, Part One

Creating shell scripts is the lazy (smart) system administrator's way to automate and build intelligence into repetitive tasks.

This scripting miniseries will help you learn some basic scripting and perhaps launch you on a more productive career in Linux system administration. If you find yourself typing the same commands over and over again, do yourself a favor and write a script to do it. Smart administrators have scripts for everything. There are three things you have to remember about scripting: Don’t test your scripts on production systems, document the script’s action, and name the script descriptively. This week’s article introduces you to simple shell scripting.

There’s no great secret to creating good scripts. You don’t have to be afraid of criticism about script security, programming style, or which editor you use to create them. You don’t need to be a programmer or even a Linux expert to create some pretty cool scripts. All you really must do is test your scripts, document your scripts, and give your scripts descriptive names.

Test your scripts to make sure they work like you expect them to. Document your scripts inside and outside the script so that you don’t forget what the script’s original purpose is and that anyone else using the script will know how to use it. Name your scripts such that its functionality is at least hinted at from the name.

Those of you who are new to Linux might ask, “Why do I need to create scripts?” The answer is simple, you don’t need to but once you’re worn out from typing the same commands several times per day, you’ll want to create them.

Scripts help you manage your system(s) more efficiently. And, the rule of thumb is, that if you’re typing it, you can script it.

The Basics

I only use the Bourne-Again Shell (BASH)* for scripting. It’s the default shell in Linux and it has the best features from the other major shells. But don’t worry if you don’t use BASH, you can still write scripts that use BASH, even if you use a different user shell. The prerequisites for gaining the most out of this series are that you know how to use basic shell commands. For example, cd, ls, ps, cat, chmod and a command line text editor such as vi, emacs, or nano.

I only use the vi** editor in the examples.

This series is interactive, so you’ll need access to a Linux system, physical or virtual, with which to work. If you’re required to use root user privileges or sudo access, I’ll note that in the example.

At the Command Line

To keep my scripts in this separate from everything else, I created an area in my home directory for them under scripts/intro. Shell scripts are simply commands contained in a file (a shell script file) that run as if you had run them individually at the command line. Enough introduction, let’s get started with some shell scripts.

Open your favorite text editor and enter some commands into it on a one command per line basis. To run the script within a BASH shell, enter #!/bin/bash.


This line, which must be the first line in your script, is the only line that may begin with the # (shell) symbol. Placed anywhere else in the script and the shell interpreter ignores it and anything on the line after it. This is the comment symbol everywhere but on the first line. Continue by adding some commands as shown.

touch file.txt
echo "Hello World" >> file.txt
echo "Create another file" > file2.txt
ls -la
cat file.txt
echo " "
cat file2.txt

Save the file with a descriptive name (no spaces) and with a .sh at the end of the name. For example, file_create.sh. The file is simply a text file, not a script at this point. Do you know why? It’s because the file permissions don’t allow execution. To change the behavior, enter the following command:

$ chmod +x file_create.sh

Now, execute the file and allow it to create the two files and display their contents.


total 20
drwxr-xr-x 2 khess khess 4096 2011-05-30 16:01 .
drwxr-xr-x 3 khess khess 4096 2011-05-30 15:35 ..
-rw-r--r-- 1 khess khess   20 2011-05-30 16:01 file2.txt
-rwxr-xr-x 1 khess khess  141 2011-05-30 15:55 file_create.sh
-rw-r--r-- 1 khess khess   12 2011-05-30 16:01 file.txt
Hello World

Create another file

As demonstrated in the script, you can enter as many commands as you want into a script. They will execute one after the other, from top to bottom, until the script completes.

For a practical application of the script you created, try this one that checks the lastlog and then mails you the list of user who’ve logged in during the current month.


echo $HOSTNAME > logins.txt
echo " " >> logins.txt
last >> logins.txt
mail ken@kenhess.com < logins.txt

Note that this file records the hostname to help you identify which hosts your messages originate from, in case you have more than one that you manage.

Interactive Scripting

What if you need more flexibility in your scripts that you just can't program to run autonomously? You program them to run interactively and provide the intelligence as needs and circumstances change.

This script prompts you for a filename, some initial content for the file, and then writes the provided information to the specified filename.


echo "Enter the name of the file you wish to create."
echo "Enter any info you want to enter into the file."
read INFO

Grant execute permission to the file and run it. Does it produce the expected results? Do you see any other useful applications for the scripts you've learned today? How about interactively adding information into a database?

Next week, you'll gain considerably more experience writing scripts now that all of the trivia and introductory material is out of the way. If you have particular problems you'd like to solve, use the Comments section to address them. Other readers might have some good ideas or I can tackle them in upcoming posts. Try out a few scripts on your own from the ones you've learned here and post them for others to use.

Remember, that we're an interactive, positive community that wants to foster open communications. Everyone comes in from a different place and it's our job to nurture learning and discovery. Until next week, happy scripting!

* Watch for my upcoming, Korn Shell tale post.

** It's the first one I learned from old UNIX nerds who thought that vi is the only editor. What can I say?

Comments on "Command Line Magic: Scripting, Part One"

These kind of insurance coverage can be
of numerous types like individual, household and
group medical insurance.

My blog post … molecule but

Companies utilizing a majority of older workers can pay 10-20 %
more to supply medical insurance, passing the expenses onto their staff members.

Check out my page :: hostage

Therefore making an accurate price contrast challenging for the majority of Irish individuals while choosing a particular insurer.

Look at my blog post health insurance california; http://thebluebreed.com/index.php/world-news/item/98-kei-nishikori-becomes-first-asian-man-to-enter-grand-slam-final,

This is a mistake you do not want to make because the more you age, the more money you will
certainly end up spending for this insurance coverage.

my homepage … cooperate note

The standard design for randomized regulated trials
in medical interventions is pricey and lengthy.

my site … http://corporate.c-istudios.com/photo-9/

There are alternative private medical insurance plans – http://www.firmaguaman.com, health insurance on the
market, but many people simply can not afford them, or they can not get accepted by one.

With the rising expenses of health care in America,
no household can truly afford to go without insurance protection.

Here is my web-site copy aisle

This is really attention-grabbing, You’re an overly professional
blogger. I have joined your feed and stay up for in search of extra of your excellent post.

Additionally, I have shared your site in my social networks

Here is my page; garcinia cambogia success stories

Do understand the area of the septic systems for small lots ontario system and also drainpipe
field, as well as keep a record of all examinations, pumpings, repairs, agreement
or design work for future recommendations.

There are some great reference sites online that could really be relied upon; and I’m not chatting
comments posted on some site that is developed to permit the
public solution inquiries; I’m speaking good individuals who concentrate on septic systems types virginia (http://toddbars.com/) systems and
also whom have absolutely nothing to shed by giving you great
solid info.

This web page connects and also organizes to our thorough septic system types ohio (coolingbedpads.xyz) tank evaluation, layout, repair, and test write-ups, including our online septic systems book.

Also visit my web blog: best place to buy diamonds online (Windy)

Also visit my blog post; reviews of regal assets [Cora]

Look into my web-site … reviews of regal assets (Weldon)

My website regal assets review, Prince,

Septic tank pumping is a solution, which is extremely necessary to work with in every home or apartment
or condo to cleanse their septic systems for small lots system.

Here is my web blog :: regal assets reviews (Maya)

Feel free to surf to my blog post; buy gold and silver tulsa ok

Look at my site … reviews of regal assets (Alta)

Also visit my homepage – reviews of regal assets – Tristan -

Filters are placed on the outlet line of your septic systems in texas – http://www.agriturismolaregina.it/eng/?p=177, system
and maintain the hair, grit, grime, food particles etc.
from leaving right into your leach area lines and creating

An expert system that has actually been checked and approved
to operate cleanly as well as without smell will most likely cost around $1,
200 to $1,500.

Also visit my web-site; septic systems maine – gifs.pornobloggers.com,

Feel free to visit my web blog; regal assets review (theconversation.com)

My blog post regal assets reviews (Rico)

my page; reviews of regal assets; Brendan,

Services that care about moving in Australia transfer to the main City from outer suburbs we will give all details and all things needed.
removalist sydney

Here is my blog: regal assets review, Refugia,

Septic system cleansing or septic tank pumping is called for to preserve the septic system system
clean as well as far from significant troubles like damage
of system, replacing brand-new septic system maintenance tips system.

The presence of healthy, lushly expanding plants around your sewage-disposal tank or along the route
of your drain lines indicates wet areas, as does a spongy or wet feel to the ground.

Also visit my site :: septic systems types in ontario

There are many SEO company in Philippines that few of them than can offer affordable services but guaranteed. SEO Consultant are everywhere but few that offer cheap, reliable, and guaranteed.
SEO Services Philippines

To be an excellent SEO expert, you have to know first the essentials of the internet such as the hypertext markup language (HTML), plunging style sheet (CSS), as
well as JavaScript.

Stop by my web blog :: seo New Farm (Kennith)

Stop by my blog post – regal assets reviews (Arlen)

Have a look at my webpage: regal assets reviews (Emmett)

my blog – reviews of regal assets (Brodie)

Here is my web site … regal assets reviews

Feel free to surf to my website – regal assets reviews [Susannah]

Take a look at my blog :: regal assets review (Felix)

The Sanctuary septic systems types virginia, Erin, Tank & Treatment
Systems has a treatment capacity of 4,800 litres.

Although specialists differ on the impacts of salt-based water softeners on standard septic system design for small lots (http://www.gamerz4life.de) tanks, many agree with the Environmental Protection Agency’s
suggestions for maintaining a septic system
working effectively.

Here is my website – regal assets review [Myra]

So if reduce losses and you wish to improve pips, obtain a Forex robot that is intelligent and place your trading on autopilot.

To acquire a better understanding of exactly how the online search engine work,
see SEO by the Sea Or, if you require assistance in building connect to your web page see The Web link Building Blog.

My page :: Kelvin Grove SEO (Beryl)

Others concern that they have a brain lump otherwise that they have
a quantity of grow of mental illness. Almost all live entertainment is
too loud to be safe for your ears regardless if it is classical, jazz, or rock.
For many of these people, their tinnitus will only last for
a short time period, whereas many others will have it for their remaining

Leave a Reply