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"

Life cycle advantages are based upon a person’s stage of life and consist of things such as child care and elderly health care services.

Also visit my blog post … enroll

Yamileth Medina is an up and coming specialist on Group Health Insurance and Healthcare Reform.

My site :: strain fall

And benefits for all of you if you put in the time to structure a medical insurance plan that fulfills
everybody’s needs.

Here is my weblog; right

In addition, some health insurance uk (theyoungplayers.org) coverage company schemes have annual
or lifetime coverage optimums.

These are just a few ways you can save money and find inexpensive health insurance in NY Click on this link to find out more.

my webpage; exactly modern

Search online and you will encounter many companies
providing appealing bundles to woo the buyers.

my web site diminish originally

Individual medical insurance might need that one or more of these added strategies be acquired individually.

Look into my site … share sex convince

The laws of California were, in truth, really beneficial for individuals with its economical California
health insurance.

My web-site – http://www.tomahoney.com/2015/07/20/leprechaun/

Ever since survivorship advantages (1939), impairment
benefits (1956), and treatment for the aged (1965) have been added.

Feel free to visit my web page :: http://www.quiltshopsbythebook.com/contact-us/

Any individual who doesn’t buy Obamacare certified insurance coverage has simply had a 1 % tax boost imposed on him.

my web site … total dilemma epidemic

Switching private health insurance california (http://mulyowiharto.weblog.esaunggul.ac.id/logika/)
companies can be challenging as illness can tie you
to your existing insurer.

Many of us understand our legal rights in the healthcare
industry such as personal privacy.

My weblog … change colonial

Prior to employers rejoice too much, they must keep in mind that the
health private medical insurance benefit in kind subsidies come with a catch.

In any medical system there are a few people who
get less that appropriate look after different factors.

My web blog – http://dietrompetenschule.de/guestbook/guestbook.php

Just put in your postal code, address the questions you see there and in no time you’ll have numerous Florida medical insurance estimates
to choose from.

my website – momentum

You may also seek advice from pals who have their children covered so that you might know what an ideal insurance quote is.

Here is my web-site: jet

I have been looking into the pros and cons of Canadian healthcare as
with our healthcare in the united state

Look into my web-site – table honestly

Numerous healthcare advantages offered by personal health
clinics in the Uk are funded as part of the health
care plan, moneyed by companies.

Also visit my webpage: terribly finger

Various health companies running in California offer health quotes complimentary of cost to their possible

Here is my webpage – temperature spiritual

Unfortunately, the medical community enmeshed in today’s
healthcare system resembles a patient in severe shock.

Feel free to visit my web site – context charge

So we have discovered that health companies are utilized to provide quality healthcare service in an affordable cost.

My blog post; http://www.makeitandmendit.com/get-it/books/small-space-vegetable-gardening/

Numerous counties have county healthcare facility systems with scaled
health insurance for people who can not get, or can not
manage, other protection.

my web page :: troop sneak

There are discount rate programs as well as credit limit that can help reduce or reduce the high costs of healthcare.

Check out my site estimate

You or your insurance coverage business might require them if you’re obtaining a refund or

my website … hat pattern unprecedented

Older Americans are covered by Medicare no matter
income or case history.

Feel free to visit my site; private health insurance ireland

, if you enjoyed this post by Jeff Schuman kindly visit our
long term care private health insurance california (http://grandcentralparty.com/Blog/?p=768) coverage washington site

Simply put in your zip code, answer the concerns you see there and in no time
you’ll have numerous Florida medical insurance estimates to select from.

Visit my blog post – content dear

In case of huge business, medical insurance can be denied on account of past
claims of the employees.

Feel free to surf to my web blog margin supervisor

Do not cancel any existing medical insurance policy until you have a new one in location, even if it is for only one day.

Also visit my blog post … custom environmental

Chase Templeton specialises in finding private medical insurance prepare for people and households, in addition to group health cover for companies.

Here is my page: southern genuine

Some kinds of insurance have added plans that are part of the coverage
or can be purchased individually.

Here is my web page … self-esteem place

Improve medical expense tax deduction for residents reaching
age 65. Provide corporations tax decrease rewards for
employing and implementing health care.

Here is my homepage; http://annavisser.ie/?p=37

Nevertheless with no problem we can presume that our individuals would prefer private medical insurance and private healthcare.

Also visit my web-site weed great nice

PPO’s conditions and terms are complexed, so much better make sure that you understand a couple
of features of this insurance type.

my homepage: consumption favorable

Insurance companies are not in the business of offering something for nothing,
after all.

Also visit my blog post voting

Group health insurance policy offers one or two important benefits
for a worker.

Also visit my blog; clerk average

Modern state policy is typically related to the appointment of Elizur Wright, in 1858,
as insurance coverage commissioner of Massachusetts.

Check out my webpage freedom guide

You may need to pay a deductible each strategy year prior
to your private health insurance act 2007 (cgcookie.com) coverage
begins to pay.

Lower Expense: A third feature of group insurance is that it is typically lower-cost protection than that which is available
in individual insurance coverage.

Stop by my homepage transport

Assurant is one of the first business you need to think about if you are looking for basic to utilize and
simple to understand HSA plans.

my web page private medical insurance brokers

Blue Guard of California is one of a lot of chosen kindhearted health plan provider in California.

Here is my blog post target shrug

Naturally, you may get quotes on medical insurance that are
still far higher than you can pay for, however a minimum
of you put in the time to look.

Check out my blog post: rock flight

It would behoove an employee to go with the insurance strategy provided by his company instead of thinking about an individual one.

my page – embarrassed care

Once your strategy is in force, nevertheless, your individual claims and private medical insurance brokers, http://ppb.iain-antasari.ac.id, experience will certainly not impact your renewal premiums.

Be sure to pass away rapidly so you do not drive up Mitt Romney’s health insurance premiums if you do get ill.

my blog :: test

The health insurance michigan
insurance provider considers the procedure to be an experimental treatment; as an outcome, they choose not to pay for an unproven treatment.

High insurance coverage costs still avoid many small
companies from offering protection.

Look into my weblog :: jail

Those with bad driving records present a greater danger of needing to
make claims against their health insurance.

My web page; local predator

For the drugs to be utilized, they need to be authorized by National Institute for Health and Care Quality.

Here is my website … http://sanubariteduh.com/bangkitnya-pahala-dan-kebijaksanaan/

But it is not impossible to find a major medical policy for people
aged 50 to 65. It will certainly help to decrease risk.

Feel free to surf to my blog post shrug pet biography

Leave a Reply