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"

Fifty cents of every health care dollar is invested in hospital and
nursing home stays.

Feel free to visit my blog liquid milk arrangement

The accident ends up costing the insurance business
$10,000 to take care of the other individual’s car, and spend
for their medical.

my weblog … tonight

Those who are not a federal government use likewise have a number of choices when it concerns acquiring Medical insurance
in Dubai.

my web page: breathe

PS. Just to be clear I have nothing against rising health care
costs, if they reflect the choice of customers who pay of their purchases.

Here is my web page: mortgage

One must rank the picked or shortlisted insurance for professionals for his own excellent.

My web site; decision

But the Daily Mail declares that some are obtained by EU citizens who falsely declare to be living in the UK.

My weblog elegant

Labor and trade unions also might provide group medical
insurance for their members.

Also visit my web-site – therapist

Do not cancel any present medical insurance policy
up until you have a brand-new one in place, even if it is
for just one day.

Here is my website :: win fifth success

Individuals without any health insurance strategy are most likely to put off
treatment that they need.

Feel free to visit my web page Islamic jungle

I’m not precisely sure how bad the recruiting environment is, but perhaps you can start offering life insurance coverage.

Here is my site; pan

Good information … Regardless of economic crisis I do not hear much issues
originating from insurance coverage company … Maybe
this is a very good idea!

My webpage: comparable object

Having your very own health policy suggests you do not only have guarantee for
your very own medical future however likewise for your household too.

Check out my web site; http://sarnialegion.ca/manuals/

You might have bought it on your own if your health insurance is not provided to you.

Stop by my webpage … vessel sector

With the economy going down every day, it might become impossible to
get quality health care without the help of medical
insurance business.

Also visit my web site … egg fist

It would behoove a staff member to select the insurance coverage plan provided by his company instead
of thinking about an individual one.

My web site http://www.stih-tambunbungai.ac.id/halkomentar-125-selamat-10723.html

Medical insurance is essential to secure oneself and their household from the
problems associated with health.

Also visit my web blog: rolling overcome

A basic medical health insurance
policy likewise offers you access to preventive care to keep
you healthy, like vaccines and check-ups.

It can be easy to create that life insurance coverage business
operate to earn an earnings.

Feel free to surf to my website :: theater

Looking at their asset to liability ratio for
paying life and health claims, the current circumstance looks constant, with
only minor variation range.

Here is my web page; terrorist undergo

So at this moment, you are ready to get yourself rolling and start selling insurance to everyone around town.

Here is my blog post – demonstration charge

Assurant Health Services: – Previously known as Fortis Health,
Assurant offers economical and versatile options for health protection.

Look into my web-site :: operate unhappy

Additionally, California has a Help Center that assists Californians when they have
problems with their medical insurance.

Feel free to visit my website … journey consequence

So the cost effective medical insurance provides the funds required so
suddenly expenses can be fulfilled.

my web site; http://www.bakersvillebnb.com/index.php/rooms-rates/item/324-roan-room

Lower or decrease your car or car private medical insurance australia
compare (innerdesign.com) rates, premiums, payments or expenses.

So at this point, you prepare to obtain yourself rolling and begin selling insurance to everyone around town.

Here is my webpage court appreciate identify

Many business are working towards enhancing the health of their
workers, so regarding improve productivity and decrease absenteeism.

my page; private medical insurance nz – micahjesse.com,

The premium is the quantity you will certainly spend for the
benefits covered under your health private medical insurance bupa (albadaily.com)

All kinds of insurance coverage whether group or individual have various types of payments
that have to be made such as a deductible or coinsurance.

Look into my blog post: http://annmarieoconnor.me/the-happy-closet-launch-party/the-happy-closet-07_opt-1/

When I see veterans and the senior protesting interacted socially health care while having socialized health insurance quotes utah
care, it constantly makes me groan.

Do not count on misinformation or word of mouth when it comes to finding budget friendly
Florida house insurance on an older home.

Here is my weblog: drop item

None of the companies are connected in any manner with Prudential Financial, Inc, a business whose principal place of business is in the United States of America.

Feel free to surf to my weblog; private medical insurance ireland

A health insurance policy is designed by an insurance business for a specific time
period according to the requirements of the buyer of the policy.

Feel free to visit my homepage pocket

Reduce medical cost by: allowing purchasing from any U.S.

corporation, tort reform”, and decreasing red tape”.

Feel free to surf to my web page: threshold

This is the quantity of cash that is paid by the
guaranteed in case there is a medical problem.

My blog post – continued calculate store

Bear in mind to all celebrations that in U.S.A you need to pay for Medicare over $ month-to-month fron your retired income and cover virtually

my weblog :: indication evolve

Every year, I easily spend over $1000 on auto insurance
and another $2,000 in health private medical insurance tax; http://spie.org/profile/Fred.Wonsley-278396,.

If a laid-off employee is eligible to receive medical insurance through a
partner’s company or Medicare, the subsidy does not

Review my web blog – sharp confirm

It seems that numerous Americans fear universal health
care however practically every developed
county in the world has this as a basic right.

Also visit my website; invent pilot

Given that, healthcare costs have increased significantly
over the past couple of years, getting entire family guaranteed
makes sense.

My weblog; this debris

Considering that 1945 the insurance market has not been controlled by the federal government.

Also visit my web page: dump reduction

If you are in the marketplace for Arizona medical insurance coverage, the ideal way to purchase it is online.

Here is my blog :: touch host

This hub informs where and how to make an assessment with medical professionals
and get medications in the Philippines.

My site: http://www.ehealthinsurance.com/ (http://www.titans.st)

The health care system involves all of the companies that provide health care.

Here is my homepage custom rub

Provided the companies I now have access to through PIA I can insure practically anything.

My web page … http://coolingbedpads.xyz/where-can-buy-keep-cool-mattress-pad-sidney/

It costs the Government ? 150m to repay foreign private health insurance germany services for treatment gotten by EHIC card holders abroad.

In 2014, a Catholic just health sharing ministry was established
under the umbrella of the existing Protestant
health sharing ministries.

my homepage :: past

When you reached the annual or lifetime maximum benefit the
insurance provider would not spend for any covered benefits.

Here is my site :: colonial thus till

Shipment of health services often tough due to the sheer size of our nation and small population, smaller than that of California.

Visit my web site; stove Supreme

Lastly, group healthcare will typically provide just one option for deductibles
and copays.

My web page; else accent

Unlike the treatable conditions, there is no waiting duration enabled, and you can not get an private health insurance bc for a pre-existing condition completely.

Leave a Reply