Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Cloud & Networking> Shell Scripting> Mastering Linux Shell Scripting
Mastering Linux Shell Scripting
Mastering Linux Shell Scripting

Mastering Linux Shell Scripting: Master the complexities of Bash shell scripting and unlock the power of shell for your enterprise

Arrow left icon
Profile Icon Andrew Mallett
Arrow right icon
$38.99
Full star iconFull star iconFull star iconFull star iconHalf star icon4.3(10 Ratings)
PaperbackDec 2015198 pages1st Edition
eBook
$9.99 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature iconInstant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Shipping Address

Billing Address

Shipping Methods
Table of content iconView table of contentsPreview book icon Preview Book

Mastering Linux Shell Scripting

Chapter 1. What and Why of Scripting with Bash

Welcome to the what and why of bash scripting. My name is Andrew Mallett and I am a bash scripting junkie or perhaps more accurately: a scripting junkie. As an administrator, I fail to see the need to do repetitive tasks manually. We get time for more interesting things when we choose scripts to carry out the laborious tasks that we don't like. In this chapter, we will introduce you to the what and why of bash scripting. If you are new, it will help you become familiar with scripts and also provide some great insights for those with more experience and who want to improve their skills. As we make our way through the chapter, each element is designed to be added to your knowledge to help you achieve your goals. While doing so, we will be covering the following topics:

  • Bash vulnerabilities
  • The bash command hierarchy
  • Preparing text editors for scripting
  • Creating and executing scripts
  • Debugging your scripts

Bash vulnerabilities

For this book, I will beworking entirely on a Raspberry Pi 2 running Raspbian, a Linux distribution similar to Debian, and Ubuntu; although for you, the operating system you choose to work with is immaterial, in reality, as is the version of bash. The bash version I am using is 4.2.37(1). If you are using the OS X operating system, the default command line environment isbash.

To return the operating system being used, type the following command if it is installed:

$ lsb_release -a

The output from my system is shown in the following screenshot:

Bash vulnerabilities

The easiest way to determine the version of bash that you are using is to print the value of a variable. The following command will display your bash version:

$ echo $BASH_VERSION

The following screenshot displays the output from my system:

Bash vulnerabilities

In 2014, there was a well-publicized bug within bash that had been there for many years—the shell-shock bug. If your system is kept up-to-date, then it is not likely to be an issue but it is worth checking. The bug allows malicious code to be executed from within a malformed function. As a standard user, you can run the following code to test for the vulnerabilities on your system. This code comes from Red Hat and is not malicious but if you are unsure then please seek advice.

The following is the code from Red Hat to test for the vulnerability:

$ env 'x=() { :;}; echo vulnerable''BASH_FUNC_x()=() { :;}; echo vulnerable' bash -c "echo test"

If your system is free from this first vulnerability the output should be as shown in the following screenshot:

Bash vulnerabilities

To test for the last vulnerability from this bug, we can use the following test, which is again from Red Hat:

cd /tmp; rm -f /tmp/echo; env 'x=() { (a)=>\' bash -c "echo date"; cat /tmp/echo

The output from a patched version of bash should look like the following screenshot:

Bash vulnerabilities

If the output from either of these command lines is different, then your system may be vulnerable to shell-shock and I would update bash or at least take further advice from a security professional.

The bash command hierarchy

When working on at the bash shell and when you are sitting comfortably at your prompt eagerly waiting to type a command, you will most likely feel that it is a simple matter of typing and hitting theEnter key. You should know better than to think that things are never quite as simple as we imagine.

Command type

For example, if we type and enterls to list files, it will be reasonable to think that we were running the command. It is possible, but we will be running an alias often. Aliases exist in memory as a shortcut to commands or commands with options; these aliases are used before we even check for the file. The bash shell built-in commandtype can come to our aid here. Thetype command will display the type of command for a given word entered at the command line. The types of command is listed as follows:

  • Alias
  • Function
  • Shell built in
  • Keyword
  • File

This list is also a representative of the order in which they are searched. As we can see, it is not until the very end where we search for the executable filels.

The following command demonstrates the simple use type:

$ type lsls is aliased to `ls --color=auto'

We can extend this further to display all the matches for the given command:

$ type -a lsls is aliased to `ls --color=auto'ls is /bin/ls

If we need to just type in the output, we can use the-t option. This is useful when we need to test thecommand type from within a script and only need the type to be returned. This excludes the superfluous information; thus, making it easier for us humans to read. Consider the following command and output:

$ type -t lsalias

The output is clear and simple and just what a computer or script requires.

The built-intype can also be used to identify shell keywords such as if, case, function, and so on. The following command shows type being used against multiple arguments and types:

$ type ls quote pwd do id

The output of the command is shown in the following screenshot:

Command type

You can also see that thefunction definition is printed when we stumble across a function when usingtype.

Command PATH

Linux will check for executables in thePATH environment only when the full or relative path to the program is supplied. Ingeneral, the current directory is not searched unless it is in thePATH. It is possible to include our current directory within thePATH by adding the directory to thePATH variable. This is shown in the following code example:

$ export PATH=$PATH:.

This appends the current directory to the value of thePATH variable each item thePATH is separated using the colon. Now, yourPATH is updated to include the current working directory and each time you change directories, the scripts can be executed easily. In general, organizing scripts into a structured directory hierarchy is probably a great idea. Consider creating a subdirectory calledbin within your home directory and add the scripts into that folder. Adding$HOME/bin to yourPATH variable will enable you to find the scripts by name and without the file path.

The following command-line list will only create the directory, if it does not already exist:

$ test -d $HOME/bin || mkdir $HOME/bin

Although the above command-line list is not strictly necessary, it does show that scripting in bash is not limited to the actual script and we can use conditional statements and other syntax directly at the command line. From our viewpoint, we know that the preceding command will work whether you have thebin directory or not. The use of the$HOME variable ensures that the command will work without considering your current file system context.

As we work through the book, we will add scripts into the$HOME/bin directory so that they can be executed regardless of our working directory.

Preparing text editors for scripting

Throughout the book, I will be working on the command line of Raspberry Pi and this will include the creation and editing of the scripts. You, of course, can choose the way you wish to edit your script and may prefer to make use of a graphical editor and I will show some settings in gedit. I will make one excursion to a Red Hat system to show screenshots of gedit in this chapter.

To help make the command line editor easier to use, we can enable options and we can persist with these options through hidden configuration files. The gedit and other GUI editors and their menus will provide similar functionality.

Configuring vim

Editing the command line is often a must and is a part of my everyday life. Setting up common options that make life easier in the editor give us the reliability and consistency you need, a little likescripting itself. We will set some useful options in the vi or vim editor file,$HOME/.vimrc.

The options we set are detailed in the following list:

  • showmode: Ensures we seewhen we are in insert mode
  • nohlsearch: Does not highlight thewords that we have searched for
  • autoindent: We indent our codeoften; this allows us to return to the last indent level rather than the start of a new line on each carriage return
  • tabstop=4: Sets a tab to be fourspaces
  • expandtab: Converts tabs tospaces, which is useful when the file moves to other systems
  • syntax on: Note that this doesnot use the set command and is used to turn on syntax highlighting

When these options are set, the$HOME/.vimrc file should look similar to this:

setshowmodenohlsearchsetautoindenttabstop=4setexpandtabsyntax on

Configuring nano

The nano text edit is increasing in importance and it is the default editor in many systems. Personally, I don't like thenavigation or the lack of navigation features that it has. It can becustomized in the same way as vim. This time we will edit the$HOME/.nanorc file. Your edited file should look something like the following:

setautoindentsettabsize 4include /usr/share/nano/sh.nanorc

The last line enables syntax highlighting for shell scripts.

Configuring gedit

Graphical editors, such as gedit, can be configured using the preferences menu and are pretty straight forward.

Enabling tab spacing to be set to4 spaces and expanding tabs to spaces can be done using thePreference |Editor tab, as shown in the following screenshot:

Configuring gedit

Tip

Downloading the example code

You can download the example code files from your account athttp://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visithttp://www.packtpub.com/support and register to have the files e-mailed directly to you.

Another very useful feature is found on thePreferences |Plugins tab. Here, we can enable theSnippets plugin that can be used to insert code samples. This is shown in the following screenshot:

Configuring gedit

For the rest of the book, we will be working on the command line in and in vim; feel free to use the editor that you work with best. We have now laid the foundations to create good scripts and although whitespace, tabs, and spaces in bash scripts are not significant; a well laid out file with consistent spacing is easy to read. When we look at Python later in the book, you will realize that in some languages the whitespace is significant to the language and it is better to adopt the good habits early.

Creating and executing scripts

With our editors primed and ready, we can now move quickly to creating and executing our scripts. If you are reading this book with some prior experience, I will warn you that we are going to startwith the basics but we will also include looking at positional parameters; feel free to move on at your own pace.

Hello World!

As you know, it is almost obligatory to begin with ahello world script and we will not disappoint as far as this is concerned. We will begin by creating a new script$HOME/bin/hello1.sh. Thecontents of the file should read as in the following screenshot:

Hello World!

I am hoping that you haven't struggled with this too much; it is just three lines after all. I encourage you to run through the examples as you read to really help you instill the information with a good hands-on practice.

  • #!/bin/bash: Normally, this is always the first line of the script and is known as the shebang. The shebang starts with a comment but the system still uses this line. A comment in a shell script has the# symbol. The shebang instructs the system to the interpreter to execute the script. We use bash for shell scripts and we may use PHP or Perl for other scripts, as required. If we do not add this line, then the commands will be run within the current shell; it may cause issues if we run another shell.
  • echo "Hello World": Theecho command will be picked up in a built-in shell and can be used to write a standard output,STDOUT, this defaults to the screen. The information to print is enclosed in double-quotes, there will be more on quotes later.
  • exit 0: Theexit command is a built in shell and is used to leave or exit the script. Theexit code is supplied as an integer argument. A value of anything other than0 will indicate some type of error in the script's execution.

Executing the script

With the script saved in ourPATH environment, it still will not execute as a standalone script. We will have to assign and execute permissions for the file, as needed. For a simple test, we can run the file directly with bash. The following command shows you how to do this:

$ bash $HOME/bin/hello1.sh

We should be rewarded with theHello World text being displayed back on our screens. This is not a long-term solution, as we need to have the script in the$HOME/bin directory, specifically, to make the running of the script easy from any location without typing the full path. We need to add in the execute permissions as shown in the following code:

$ chmod +x $HOME/bin/hello1.sh

We should now be able to run the script simply, as shown in the following screenshot:

Executing the script

Checking the exit status

This script is simple butwe still have to know how to make use of the exit codes from scripts and other applications. The command-line list that we generated earlier while creating the$HOME/bin directory, is a good example of how we can use the exit code:

$ command1 || command 2

In the preceding example,command2 is executed only ifcommand1 fails in some way. To be specific,command2 will run ifcommand1 exits with a status code other than0.

Similarly, in the following extract:

$ command1 && command2

We will only executecommand2 ifcommand1 succeeds and issues an exit code of0.

To read the exit code from our script explicitly, we can view the$?variable, as shown in the following example:

$ hello1.sh$ echo $?

The expected output is0, as this is what we have added to the last line of the file and there is precious little else thatcan go wrong causing us to fail in reaching that line.

Ensuring a unique name

We can now createand execute a simple script but we need to consider the name a little. In this case,hello1.sh is going to be good enough and is unlikely to clash with anything else on the system. We should avoid using names that may clash with existing aliases, functions, keywords, and building commands, as well as, avoid names of programs already in use.

Adding thesh suffix to the file does not guarantee the name to be unique but in Linux, where we do not file extensions, the suffix is a part of the file name. This helps you to provide a unique identity to your script. Additionally, the suffix is used by the editor to help you identify the file for syntax highlighting. If you recall, we specifically added the syntax highlighting filesh.nanorc to the nano text editor. Each of these files is specific to a suffix and subsequent language.

Referring back to the command hierarchy within this chapter, we can use a type to determine the location and type of filehello.sh is:

$ type hello1.sh  #To determine the type and path$ type -a hello1.sh  #To print all commands found if the name is NOT unique$ type -t hello1.sh ~To print the simple type of the command

These commands and output can be seen in the following screenshot:

Ensuring a unique name

Hello Dolly!

It is possible that we might need a little more substance in the script than a simple fixed message. Static message content does have its place but we can make this script much more useful by building some flexibility.

In this chapter, we will look atpositional parameters or arguments that we can supply to the script and in the next chapter we will see how we can make the script interactive and also prompt the user for input at runtime.

Running the script with arguments

We can run thescript with arguments, after all it's a free world and Linux promotes your freedom to do what you want to do with the code. However, if the script does not make use of the arguments, then they will be silently ignored. The following code shows the script running with a single argument:

$ hello1.shfred

The script will still run and will not produce an error. The output will not change either and will print hello world:

Argument Identifier

Description

$0

The name of the script itself and is often used in usage statements.

$1

Positional argument, the first argument passed to the script.

${10}

Where two or more digits are needed to represent the argument position. Brace brackets are used to delimit the variable name from any other content. Single value digits are expected.

$#

Argument count is especially useful when we need to set the amount of arguments needed for correct script execution.

$*

Refers to allarguments.

For the script to make use of the argument, we can change the script content a little. Let's first copy the script, add in the execute permissions, and then edit the newhello2.sh:

$ cp $HOME/bin/hello1.sh $HOME/bin/hello2.sh$ chmod +x $HOME/bin/hello2.sh

We need to edit thehello2.sh file to make use of the argument as it is passed at the command line. The following screenshot shows the simplest use of command line arguments allowing us now to have a custom message.

Running the script with arguments

Run the script now, we can provide an argument as shown in the following:

$ hello2.sh fred

The output should now sayHello fred. If we do not provide an argument then the variable will be emptyand will just printHello. You can refer to the following screenshot to see the execution argument and output:

Running the script with arguments

If we adjust the script to use$*, all the arguments will print. We will seeHello and then a list of all the supplied arguments. If we edit the script and replace theecho line as follows:

echo "Hello $*"

Executing the script with the following arguments:

$ hello2.shfredwilma  betty barney

Will result in the output shown in the following screenshot:

Running the script with arguments

If we want to printHello <name>, each on separate lines, we will need to wait a little until we cover the looping structures. A for loop will work well to achieve this.

The importance of correct quotes

So far, we have used a simple double quoting mechanism to encase the strings that we want to use with echo.

In the first script, it does not matter if we use single or double quotes. Theecho "Hello World" will be exactly the same asecho 'Hello World'.

However, this will not be the case in the second script so it is very important to understand the quoting mechanisms available in bash.

As we have seen, using the double quotesecho "Hello $1" will result inHello fred or whatever the supplied value is. Whereas, if we use single quotesecho 'Hello $1' the printed output on the screen will beHello $1, where we see the variable name and not its value.

The idea of the quotes is to protect the special character such as a space between the two words; both quotes protect the space from being interpreted. The space is normally read as a default field, separated by the shell. In other words, all characters are read by the shell as literals with no special meaning. This has the knock on effect of the$ symbol printing its literal format rather than allowing bash to expand its value. The bash shell is prevented from expanding the variable's value, as it is protected by the single quotes.

This is where the double quote comes to our rescue. The double quote will protect all the characters except the$, allowing bash to expand the stored value.

If we ever need to use a literal$ within the quoted string along with variables that need to be expanded; we can use double quotes but escape the desired$ with the backslash (\). For example,echo "$USER earns \$4" would print asFred earns $4 if the current user was Fred.

Try the following examples at the command line using all quoting mechanisms. Feel free to up your hourly rate as required:

$ echo "$USER earns $4"$ echo '$USER earns $4'$ echo "$USER earns \$4"

The output is shown in the following screenshot:

The importance of correct quotes

Printing the script name

The$0 variable represents the script name and this is often used in usage statements. As we are not yet looking at conditional statements, we will have the script name printed above the displayed name.

Edit your script so that it reads as the following complete code block for$HOME/bin/hello2.sh:

#!/bin/bashecho "You are using $0"echo "Hello $*"exit 0

The output from the command is shown in the following screenshot:

Printing the script name

If we prefer not to print the path and only want the name of the script to show we can use thebasename command, which extracts the name from the path. Adjusting the script so that the second line now reads is as follows:

echo "You are using $(basename $0)"

The$(….) syntax is used to evaluate the output of the inner command. We first runbasename $0 and feed the result into an unnamed variable represented by the$.

The new output will appear as seen in the following screenshot:

Printing the script name

It is possible to achieve the same results using back quotes, this is less easy to read but we have mentioned this asyou might have to understand and modify the scripts that have been written by others. The alternative to the$(….) syntax is shown in the following example:

echo "You are using 'basename $0'"

Please note that the characters used are back quotes andNOT single quotes. On UK and US keyboards, these are found in the top-left section next to the number1 key.

Debugging your scripts

With the scripts as simple as we have seen so far, there is little that can go wrong or debug. As the script grows and decision paths are included with conditional statements, we may need to use some level of debugging to analyze the scripts progress better.

Bash provides two options for us,-v and-x.

If we want to lookat the verbose output from our script and the detailed information about the way the script is evaluated line by line, we can use the-v option. This can be within the shebang but it is often easier to run the script directly with bash:

$ bash -v $HOME/bin/hello2.sh fred

This is especially useful in this example as we can see how each element of the embeddedbasename command is processed. The first step is removing the quotes and then the parentheses. Take a look at the following output:

Debugging your scripts

More commonly used is the-x option, which displays the commands as they get executed. Its useful to know the decision branch that has been chosen by the script. The following shows this in use:

$ bash -x $HOME/bin/hello2.sh fred

We again see that thebasename is evaluated first, but we do not see the more detailed steps involved in running that command. The screenshot that follows captures the command and output:

Debugging your scripts

Summary

This marks the end of the chapter and I am sure that you might have found this useful. Especially for those making a start with bash scripting, this chapter must have built a firm foundation on which you can build your knowledge.

We began by ensuring that bash is secure and not susceptible to embedded functions shell-shock. With bash secured, we considered the execution hierarchy where aliases, functions, and so on are checked before the command; knowing this can help us plan a good naming structure and a path to locate the scripts.

Soon we were writing simple scripts with static content but we saw how easy it was to add flexibility using arguments. The exit code from the script can be read with the$? variable and we can create a command line list using|| and&&, which depends on the success or failure of the preceding command in the list.

Finally, we closed the chapter by looking at debugging the script. Its not really required when the script is trivial, but it will be useful later when complexity is added.

In the next chapter, we will be creating interactive scripts that read the user's input during script execution.

Left arrow icon

Page1 of 7

Right arrow icon

Key benefits

  • Identify the high level steps such as verifying user input, using command lines and conditional statements in creating and executing simple shell scripts
  • Create and edit dynamic shell scripts to manage complex and repetitive tasks
  • Learn about scripting in Perl and programming in Python as a BASH scripting alternative with this practical, step-by-step guide

Description

Shell scripting is a quick method to prototype a complex application or a problem by automating tasks when working on Linux-based systems. Using both simple one-line commands and command sequences complex problems can be solved with ease, from text processing to backing up sysadmin tools.In this book, you’ll discover everything you need to know to master shell scripting and make informed choices about the elements you employ. Get to grips with the fundamentals of creating and running a script in normal mode, and in debug mode. Learn about various conditional statements' code snippets, and realize the power of repetition and loops in your shell script. Implement functions and edit files using the Stream Editor, script in Perl, program in Python – as well as complete coverage of other scripting languages to ensure you can choose the best tool for your project.

Who is this book for?

Mastering Linux Shell Scripting has been written for Linux administrators who want to automate tasks in their daily lives, saving time and effort. You’ll need to have command-line experience and be familiar with the tasks that you need to automate.

What you will learn

  • * Use the type command to identify the order of command evaluation
  • * Create interactive scripts that prompt for user input
  • * Foster menu structures for operators with little command-line experience
  • * Develop scripts that dynamically edit web configuration files to produce a new virtual host
  • * Write scripts that use AWK to search and reports on log files
  • * Draft effective scripts using functions as building blocks, reducing maintenance and build time
  • * Make informed choices by comparing different script languages such as Perl and Python with BASH
Estimated delivery feeDeliver to Argentina

Standard delivery10 - 13 business days

$12.95

Premium delivery3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Dec 24, 2015
Length:198 pages
Edition :1st
Language :English
ISBN-13 :9781784396978
Tools :

What do you get with Print?

Product feature iconInstant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Shipping Address

Billing Address

Shipping Methods
Estimated delivery feeDeliver to Argentina

Standard delivery10 - 13 business days

$12.95

Premium delivery3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Publication date :Dec 24, 2015
Length:198 pages
Edition :1st
Language :English
ISBN-13 :9781784396978
Category :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99billed monthly
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconSimple pricing, no contract
$199.99billed annually
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts
$279.99billed in 18 months
Feature tick iconUnlimited access to Packt's library of 7,000+ practical books and videos
Feature tick iconConstantly refreshed with 50+ new titles a month
Feature tick iconExclusive Early access to books as they're written
Feature tick iconSolve problems while you work with advanced search and reference features
Feature tick iconOffline reading on the mobile app
Feature tick iconChoose a DRM-free eBook or Video every month to keep
Feature tick iconPLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick iconExclusive print discounts

Frequently bought together


Mastering Linux Shell Scripting
Mastering Linux Shell Scripting
Read more
Dec 2015198 pages
Full star icon4.3 (10)
eBook
eBook
$9.99$29.99
$38.99
Learning Linux Shell Scripting
Learning Linux Shell Scripting
Read more
Dec 2015306 pages
Full star icon4.8 (6)
eBook
eBook
$9.99$43.99
$54.99
Linux Shell Scripting Essentials
Linux Shell Scripting Essentials
Read more
Nov 2015282 pages
Full star icon4.5 (2)
eBook
eBook
$9.99$43.99
$54.99
Stars icon
Total$148.97
Mastering Linux Shell Scripting
$38.99
Learning Linux Shell Scripting
$54.99
Linux Shell Scripting Essentials
$54.99
Total$148.97Stars icon
Buy 2+ to unlock$7.99 prices - master what's next.
SHOP NOW

Table of Contents

15 Chapters
1. What and Why of Scripting with BashChevron down iconChevron up icon
1. What and Why of Scripting with Bash
Bash vulnerabilities
The bash command hierarchy
Preparing text editors for scripting
Creating and executing scripts
Debugging your scripts
Summary
2. Creating Interactive ScriptsChevron down iconChevron up icon
2. Creating Interactive Scripts
Using echo with options
Basic script using read
Script comments
Enhancing scripts with read prompts
Limiting the number of entered characters
Controlling the visibility of entered text
Enhancing learning with simple scripts
Summary
3. Conditions AttachedChevron down iconChevron up icon
3. Conditions Attached
Simple decision paths using command-line lists
Verifying user input with lists
Using the test shell builtin
Creating conditional statements using if
Extending if with else
More conditions with elif
Using case statements
Script – building a front-end with grep
Summary
4. Creating Code SnippetsChevron down iconChevron up icon
4. Creating Code Snippets
Abbreviations
Using code snippets
Summary
5. Alternative SyntaxChevron down iconChevron up icon
5. Alternative Syntax
Recapping test
Providing parameter defaults
When in doubt – Quote!
Advanced test using [[
Arithmetic operations using ((
Summary
6. Iterating with LoopsChevron down iconChevron up icon
6. Iterating with Loops
For loops
Controlling the loop
Reading input from files
Creating operator menus
Summary
7. Creating Building Blocks with FunctionsChevron down iconChevron up icon
7. Creating Building Blocks with Functions
Introducing functions
Passing parameters to functions
Returning values from functions
Using functions in menus
Summary
8. Introducing sedChevron down iconChevron up icon
8. Introducing sed
Using grep to display text
Using regular expressions
Understanding the basics of sed
Summary
9. Automating Apache Virtual HostsChevron down iconChevron up icon
9. Automating Apache Virtual Hosts
Apache name-based Virtual Hosts
Automating Virtual Host creation
Summary
10. Awk FundamentalsChevron down iconChevron up icon
10. Awk Fundamentals
The history behind awk
Displaying and filtering content from files
Formatting output
Further filtering to display users by UID
Awk control files
Summary
11. Summarizing Logs with AwkChevron down iconChevron up icon
11. Summarizing Logs with Awk
The HTTPD log file format
Displaying data from web logs
Displaying the highest ranking IP address
Displaying the browser data
Working with e-mail logs
Summary
12. A Better lastlog with AwkChevron down iconChevron up icon
12. A Better lastlog with Awk
Using awk ranges to exclude data
Conditions based on the number of fields
Manipulating the awk record separator to report on XML data
Summary
13. Using Perl as a Bash Scripting AlternativeChevron down iconChevron up icon
13. Using Perl as a Bash Scripting Alternative
What is Perl?
Hello World
Perl arrays
Conditional statements in Perl
Using functions within Perl
Summary
14. Using Python as a Bash Scripting AlternativeChevron down iconChevron up icon
14. Using Python as a Bash Scripting Alternative
What is Python?
Saying Hello World the Python way
Pythonic arguments
Significant whitespace
Reading user input
Summary
IndexChevron down iconChevron up icon
Index

Recommendations for you

Left arrow icon
Solutions Architect's Handbook
Solutions Architect's Handbook
Read more
Mar 2024582 pages
Full star icon4.6 (57)
eBook
eBook
$9.99$47.99
$59.99
Mastering Terraform
Mastering Terraform
Read more
Jul 2024506 pages
Full star icon5 (21)
eBook
eBook
$9.99$39.99
$49.99
The Ultimate Linux Shell Scripting Guide
The Ultimate Linux Shell Scripting Guide
Read more
Oct 2024696 pages
Full star icon4.9 (8)
eBook
eBook
$9.99$39.99
$49.99
Kubernetes – An Enterprise Guide
Kubernetes – An Enterprise Guide
Read more
Aug 2024682 pages
Full star icon4.8 (13)
eBook
eBook
$9.99$43.99
$54.99
The Self-Taught Cloud Computing Engineer
The Self-Taught Cloud Computing Engineer
Read more
Sep 2023480 pages
Full star icon5 (180)
eBook
eBook
$9.99$39.99
$49.99
CI/CD Design Patterns
CI/CD Design Patterns
Read more
Dec 2024356 pages
eBook
eBook
$9.99$31.99
$39.99
Platform Engineering for Architects
Platform Engineering for Architects
Read more
Oct 2024374 pages
Full star icon5 (2)
eBook
eBook
$9.99$39.99
$49.99
Microsoft Azure Fundamentals Certification and Beyond
Microsoft Azure Fundamentals Certification and Beyond
Read more
Jan 2024284 pages
Full star icon4.8 (29)
eBook
eBook
$9.99$35.99
$44.99
The Ultimate Docker Container Book
The Ultimate Docker Container Book
Read more
Aug 2023626 pages
Full star icon4 (8)
eBook
eBook
$9.99$39.99
$49.99
Right arrow icon

Customer reviews

Top Reviews
Rating distribution
Full star iconFull star iconFull star iconFull star iconHalf star icon4.3
(10 Ratings)
5 star70%
4 star10%
3 star10%
2 star0%
1 star10%
Filter icon Filter
Top Reviews

Filter reviews by




SuJoFeb 27, 2016
Full star iconFull star iconFull star iconFull star iconFull star icon5
I was extremely skeptical at first glance; however after reading this book it truly covers each topic with enough detail to give a clear understanding of the tasks at hand. Doing a lot of automation work with frameworks like Puppet which can benefit from shell scripts, and all I can say is wow.. you really need to pickup a copy of this book as it is well worth the cost.
Amazon Verified reviewAmazon
C.P.Feb 26, 2017
Full star iconFull star iconFull star iconFull star iconFull star icon5
This book so far has been very useful and I am very pleased with the contents so far. I have read about 1/3 and so far an A+ from me.
Amazon Verified reviewAmazon
Mark SmithApr 16, 2016
Full star iconFull star iconFull star iconFull star iconFull star icon5
Great Book and highly recommend.
Amazon Verified reviewAmazon
Perry NallyMar 02, 2016
Full star iconFull star iconFull star iconFull star iconFull star icon5
Almost all you need, and certainly all you need to get you up and running. Gave me the ins and outs of the bash shell as well as pointed me in the right direction with the intro to Peral and Python as additional resources to use when bash shell does allow my to do what I need. I'll have this book as a reference for a very long time when I start building linux embedded devices. I know I'll be turning to this book for references on creating the scripts I need.
Amazon Verified reviewAmazon
Tim CrothersMar 10, 2016
Full star iconFull star iconFull star iconFull star iconFull star icon5
Really, really good coverage of bash scripting core fundamentals. Literally one of the best I've read and I've read many of them. I wouldn't go nearly as far as to say complete as some of the other reviews have stated but it definitely does a really good job of getting you started down the road. The only issue I had in the end is the "mastering" part of the title. I don't think any book under 200 pages should claim to provide mastery of a topic, especially one as complex as bash shell scripting, but in the end I decided not to dock it a start because it does such a good job at what it does cover. My preference would be to drop the small sections on Perl and Python. They are topics worthy of their own treatment and the pages could have been put to better use going deeper on shell scripting.
Amazon Verified reviewAmazon
  • Arrow left icon Previous
  • 1
  • 2
  • Arrow right icon Next

People who bought this also bought

Left arrow icon
Mastering Ubuntu Server
Mastering Ubuntu Server
Read more
Sep 2022584 pages
Full star icon4.6 (36)
eBook
eBook
$9.99$43.99
$54.99
The Ultimate Docker Container Book
The Ultimate Docker Container Book
Read more
Aug 2023626 pages
Full star icon4 (8)
eBook
eBook
$9.99$39.99
$49.99
Mastering Kubernetes
Mastering Kubernetes
Read more
Jun 2023746 pages
Full star icon4.6 (45)
eBook
eBook
$9.99$43.99
$54.99
Ansible for Real-Life Automation
Ansible for Real-Life Automation
Read more
Sep 2022480 pages
Full star icon3.9 (7)
eBook
eBook
$9.99$33.99
$41.99
AWS for Solutions Architects
AWS for Solutions Architects
Read more
Apr 2023696 pages
Full star icon4.3 (62)
eBook
eBook
$9.99$59.99
$79.99
Right arrow icon

About the author

Profile icon Andrew Mallett
Andrew Mallett
Andrew Mallett has been working professionally with Linux since 1999; much of that time as an Instructor. He now runs his consultancy where he works with and writes about Linux. He is onto his 5th book with Packt and has 65,000 subscribers on his YouTube channel: theurbanpenguin. You can be assured that he masters Linux and is passionate to share his knowledge with you.
Read more
See other products by Andrew Mallett
Getfree access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order?Chevron down iconChevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book?Chevron down iconChevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium:Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge?Chevron down iconChevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order?Chevron down iconChevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries:www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges?Chevron down iconChevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live inMexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live inTurkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order?Chevron down iconChevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy?Chevron down iconChevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged?Chevron down iconChevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use?Chevron down iconChevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books?Chevron down iconChevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium:Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela

Create a Free Account To Continue Reading

Modal Close icon
OR
    First name is required.
    Last name is required.

The Password should contain at least :

  • 8 characters
  • 1 uppercase
  • 1 number
Notify me about special offers, personalized product recommendations, and learning tips By signing up for the free trial you will receive emails related to this service, you can unsubscribe at any time
By clicking ‘Create Account’, you are agreeing to ourPrivacy Policy andTerms & Conditions
Already have an account? SIGN IN

Sign in to activate your 7-day free access

Modal Close icon
OR
By redeeming the free trial you will receive emails related to this service, you can unsubscribe at any time.

[8]ページ先頭

©2009-2025 Movatter.jp