Bash Shell

Bash Shell

A shell is a special program which gives you the familiar text mode prompt. You can use it to start other programs and it understands some special commands of its own.

There are several different shell programs in use in Linux. One of them is the Bourne Again Shell (BASH). Bash has more advanced features and it is more user-friendly.

Bash relies on an number of startup files, which comtain bash commands. The shell executes these commands just as if they had been typed at the command prompt. These files include the following:

/etc/profile

/etc/bashrc

~/.bash_profile, ~/.bash_login, and ~/.profile

~/.bashrc

~/.bash_logout

/etc/inputrc

~/.inputrc

Shell Command Syntax

You can enter most commands by typing the command’s name, following by a space and the options and arguments you want to use.

$ command-name   options   arguments

To create more complex commands, you need to learn the fundamentals of bash’s syntax.

Special Characters and Quoting

Metacharacters

Command Sequences and Groups

Input/Output Redirection

Brace Expansion

Tilde Expansion

Command Substitution

History Expansion

Parameter Expansion

Shell Functions

Job Control

Special Characters and Quoting

Certain characters have a special meaning to bash. If you want to use these characters in a way other than how bash interprets them, you must enclose them in quotation mark.

 

Special Character

Purpose

Quotes all of the enclosed text, preventing all expansions or substitutions.

!

A logical NOT in a command sequence.

“”

Quotes the enclosed text with the exception of variable expansion and command substitution.

#

Comment

$

Inserts a named variable

&

When appended to a command name, executes the command in the background.

&&

A logical AND in a command sequence.

( )

Groups commands for execution by a subshell. It is also used to identify a function.

*

Stands zero for any characters in a shell pattern.

./

When placed at the beginning of the line, executes a command in the working directory.

?

Stands for any one character in a shell pattern.

[ ]

Defines a character class in a shell pattern.

\

Quotes the following character.

Indicates a command substitution.

{ }

Groups commands. Also used for brace expansion.

|

Redirects the command output to a second command.

||

A logical OR in a command sequence.

<

Takes input from a file.

<<

Uses the standard input but only up to the specified text.

>

Redirects the command output to a file.

>>

Appends the command output to a file.

%

Indicates a job number.

 

Metacharacters

A metacharacter is a special character that functions as a word seperator, as if it were a blank space. However, not all special characters are metacharacters.

 

Metacharacter

Purpose

|

Pipelline

&

Command Substitution

;

Command Seperator

()

Command grouping for execution in a subshell

<>

Redirection Operators

 

example:

$ cat ‘test # testing.txt’

Display the text of a file with special character.

$ dir “$pwd/chapter(overview)”

Specifies a directory to be displayed using command substitution ($pwd). But the double quotation marks protect the paranthesis from interpretation by the shell.

$ gunzip linux.tar.gz ; tar -xvf linux.tar

Unzips linux.tar.gz and extracts the files from the archive.

$ { find linux* ; find unix* ; }| less

Locates all the files that start with linux and unix, and pipes the output to the less command. Spaces are needed before the curly braces but not before the vertical bar as it is a metacharacter.

Command Sequences and Groups

You can type more than one command on a single line so that they are executed together in the specified sequence from left to right.

 

Command Form

Meaning

cmd1 ; cmd2

Execute cmd1, then execute cmd2

(cmd1 ; cmd2)

In a subshell, execute cmd1, then execute cmd2

{cmd1 ; cmd2}

In the current shell, execute cmd1, then execute cmd2

cmd1 && cmd2

Execute cmd2 only if cmd1 succeeds

cmd1 || cmd2

Execute cmd2 only if cmd1 fails

 

example:

 

$ find README && cat README

Displays the README file only if the find command succeeds.

 

$ find README.bak || cp README README.bak

Makes a backup of README only if the find command fails.

 

Brace Expansion
With brace expansion, you can generate two or more commands from a single typed command. When bash encounters a brace character, it reads the comma-seperated list inside the braces from left to right. One by one, it uses the strings within the braces to form a series of commands.

example:

$ cp linux/{ppp,mgetty,vgetty} /mnt

This is equivalent to this:

$ cp linux/ppp /mnt

$ cp linux/mgetty /mnt

$ cp linux/vgetty /mnt

Tilde Expansion

With tilde expansion, you can quickly enter directory names. The following table, Tilde Prefixes, lists the ways you can use tildes to enter directory names.

 

Tilde Prefixes:

~

Insert the current user’s home directory

~/subdirectory

Insert a path name that begins with the user’s home directory and includes subdirectory

~+

Insert the name of the current directory

~-

Insert the name of the previous directory

Command Substitution

With command substitution, you can insert the output of a command within a command that you are creating.

 

`command`

 

example:

 

$ ls `pwd`

Displays the contents of the current directory

Parameter Expansion

A shell parameter is an entity that stores a value. Among various types of shell parameters are variables. You can create your own variables and assign values to them. You can also make use of several built-in variables.

 

Creating and Using Variables

 

name=value

Create a variable called name and assign value to this variable.

 

$name

Insert the value of a name.

 

Some Built-In Variables:

$BASH

Location of bash.

$BASH_ENV

The location of current .bashrc file in use.

$BASH_VERSION

The version number of bash.

$GROUPS

An array variable listing the groups to which the current user belongs.

$HISTFILE

The location of the bash history file in current use.

$HISTFILESIZE

The maximum size of the current history file.

$HOME

The current user’s home directory.

$HOSTNAME

The system’s host name.

$MAIL

The location of the current user’s mailbox.

$PATH

The directories used to search for executables.

$PS1

The values and text used to define the bash prompt.

$PWD

The current directory.

$RANDOM

A random number

$SECONDS

The number of seconds since bash was started

$SHELL

The current shell

$SHLVL

The number of times new shells have been started.

$UID

The current user’s numerical ID number

$USER

The current user’s name.

 

 

History Expansion

The shell keeps track of the commands you have entered. It does so by creating a history list in which each command is given a unique identifying number. You can use the history list expansion to insert commands from the history list.

 

!n

Enter the nth command in the history list.

!!

Enter the previous command.

!-n

Enter the nth command back from the current command.

!string:p

Display the most recent command that starts with string.

!string

Enter the most recent command that starts with string.

!?string?

Enter the most recent command that contains string.

!$

Enter the last argument of the previous command.

!!string

Enter the previous command and append string.

!n string

Enter the nth command in the history list and append string.

!(string1)string2

Enter the most recent command that starts with string1 and append string2

^string1^string2

Change string1 from previous command to string2, and execute command.

 

 

History Command

The history command displays a numbered list of the commands in the history list. You can specify the maximum number of lines to display. If the history list contains more lines than you specified, you see the most recently used commands.

 

<<General format>>

$ history [option] [lines]

Options:

-a

Write current session’s commands to .bash_history

-n

Add to .bash_history any commands that are not yet listed in the history list.

-r

Use .bash_history as the history list, discarding commands used in the current session.

-w

Overwrite .bash_history with the commands used in this session.

Configuring History

The number of events saved by your system is kept in a special system variable called HISTSIZE. By default this is usually set to 500. You can change this to another number by simply assigning new value to HISTSIZE and exporting it.

 

example:

$ HISTSIZE=1000

$ export HISTSIZE

or

$ export HISTSIZE=1000

 

To display the current value of an environment variable, use the echo command.

$ echo $HISTSIZE

 

The actual histroy events are saved in a file whose name is held in a special variable called HISTFILE. By default this file is the .bash_history file in your home directory. However, you can change the file in which history events are saved by assigning its name to the HISTFILE variable.

 

example:

$ HISTFILE=”.myhistory” ; export HISTFILE

 

Shell Functions

A shell function is a new command with the name you specify. The shell function executes all the commands listed within the curly braces.

 

<<General format>>

[ function ] name { command1; command2;…;}

Creates a function called name that includes the specified commands.

 

name () { command1; command2;…;}

Creates a function called name that includes the specified commands.

 

example:

 

$ list () { ls -al | less; }

Creates a shell function called list that executes the ls command and pipes its output to less.

 

Shell Configuration Files

Several configuration files support how your shell behaves. Some of these files are executed for every user and every shell. Others are specific to the particular user that creates the configuration file. These files are:

 

/etc/profile

This file sets up user environment information for every user. It is executed when you first log in and the shell starts. This file provides values for your path and maximum file size that you can create. It also sets environment variables for such things as location of your mailbox and size of your history files. Finally, /etc/profile gathers shell settings from configuration files in the /etc/profile.d directory.

 

/etc/bashrc

 

This file is executed for every user that runs the bash shell. It is read each time a bash shell is opened. It sets the default prompt and may add one or more aliases. Values in this file can be overridden by information in each user’s ~/.bashrc file.

 

~/.bash_profile

 

This file is used by each user to enter information that is specific to their own use of the shell. It is executed only once, when the user logs in. By default its sets a few environment variables and executes the user’s .bashrc file.

 

~/.bashrc

 

This file contains the bash information that is specific to your bash shells. It is read when you log in and also each time you open a new bash shell. This is the best location to add environment variables and aliases so that your shell picks them up.

 

~/.bash_logout

 

This file executes each time you log out (exit the last bash shell). By default, it simply clears your screen.

 

To change the /etc/profile or /etc/bashrc files, you must be the root user. Any user can change the information in $HOME/.bash_profile, $HOME/.bashrc, and $HOME/.bash_logout files in their own home directories.

Setting Your Prompt

Your prompt consists of a set of characters that appear each time the shell is ready to accept a command. Exactly what that prompt contains is determined by the value in PS1 environment variable. Here is an example of the prompt.

 

[kundan@linuxnepal tmp]$

 

If you were to change directories, the tmp name would change to the name of the new current working directory. Likewise, if you were to log in as a different user or to a different host, that information would change.

 

You can use several special characters to include different information in your prompt.

 

Some of the examples are:

 

\!

Shows the current command history number. This includes all previous commands stored for your username.

 

\#

Shows the command number of the current command. This includes only the commands for the active shell.

 

\$

Shows the standard user prompt ($) or root prompt (#), depending on which user you are.

 

\W

Shows only the current working directory base name. For example, if the current directory was /var/spool/mail, this value would simply appear as mail.

 

\\

Shows a backslash.

 

\d

Displays the day, month, and the number of the date. eg: Fri Jun 11

 

\h

Shows the host name of the computer running the shell.

 

\n

newline

 

\nnn

Shows the character that relates to the octal number replacing nnn.

 

\s

Displays the current shell name. bash for bash shell.

 

\t

Prints the current time in hours, minutes, and seconds. eg: 12:10:44

 

\u

Prints the current user name.

 

\w

Displays the full path to the current working directory.

Adding Environment Variables

You can add your own environment variables into your .bashrc file. These can help make working with the shell more efficient and effective. You can update your $PATH environment variables like:

 

PATH=$PATH:/myprogs/bin ; export $PATH

 

This example first reads all the current path directories into the new PATH ($PATH), adds the /myprogs/bin directory, and then exports the new PATH.

 

You can create your own environment variables to provide shortcuts in your work. Choose any name that is not being used and assign a useful value for it.

 

PF=/usr/share/project/info ; export PF

 

You can change to this directory by issuing command as:

 

$ cd $PF

 

 

 

Adding Aliases

Setting aliases can save you even more typing than setting environment variables. With aliases, you can have a string of characters execute an entire command line. You can add and list aliases with the alias command.

 

example:

 

alias p=’pwd ; ls -alF’

alias rm=’rm -i’

 

In the first command the letter p is assigned to run the command pwd, and then to run

ls -alF to print the current directory and list its contents.

The second example runs the rm command with the -i option each time you type rm.

 

When you are in the shell, you can check which aliases are set by simply typing the alias command.

 

If you want to remove an alias, you can use the unalias command. If the alias is set in a configuration file like .bashrc, it will be set again when you open another shell.

eg:

 

To remove alias named p

$ unalias p

To remove all of your aliases

$ unalias -a

Leave a Reply

Your email address will not be published. Required fields are marked *


*

The only Linux site of Nepal