27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11. Internal Commands and Builtins<br />

A builtin is a command contained within the Bash tool set, literally built in. This is either for performance<br />

reasons −− builtins execute faster than external commands, which usually require forking off a separate<br />

process −− or because a particular builtin needs direct access to the shell internals.<br />

When a command or the shell itself initiates (or spawns) a new subprocess to carry out a task, this is called<br />

forking. This new process is the "child", and the process that forked it off is the "parent". While the child<br />

process is doing its work, the parent process is still executing.<br />

Generally, a Bash builtin does not fork a subprocess when it executes within a script. An external system<br />

command or filter in a script usually will fork a subprocess.<br />

A builtin may be a synonym to a system command of the same name, but Bash reimplements it internally. For<br />

example, the Bash echo command is not the same as /bin/echo, although their behavior is almost<br />

identical.<br />

#!/bin/bash<br />

echo "This line uses the \"echo\" builtin."<br />

/bin/echo "This line uses the /bin/echo system command."<br />

A keyword is a reserved word, token or operator. Keywords have a special meaning to the shell, and indeed<br />

are the building blocks of the shell's syntax. As examples, "for", "while", "do", and "!" are keywords. Similar<br />

to a builtin, a keyword is hard−coded into Bash, but unlike a builtin, a keyword is not by itself a command,<br />

but part of a larger command structure. [24]<br />

I/O<br />

echo<br />

prints (to stdout) an expression or variable (see Example 4−1).<br />

echo Hello<br />

echo $a<br />

An echo requires the −e option to print escaped characters. See Example 5−2.<br />

Normally, each echo command prints a terminal newline, but the −n option suppresses this.<br />

An echo can be used to feed a sequence of commands down a pipe.<br />

if echo "$VAR" | grep −q txt # if [[ $VAR = *txt* ]]<br />

then<br />

echo "$VAR contains the substring sequence \"txt\""<br />

fi<br />

An echo, in combination with command substitution can set a variable.<br />

Chapter 11. Internal Commands and Builtins 124

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!