Licão 07 operating the shell

55
Lesson 7 Bash Keywords Command-Line Editing Variable Assignments and Displaying Messages Multiple Commands – printf Command History Directory Commands – pwd Specialized Navigation and History Colon Command Shell Aliases Bash Hash Table Job States

Transcript of Licão 07 operating the shell

Page 1: Licão 07 operating the shell

Lesson 7• Bash Keywords

• Command-Line Editing

• Variable Assignments and Displaying Messages

• Multiple Commands – printf

• Command History

• Directory Commands – pwd

• Specialized Navigation and History

• Colon Command

• Shell Aliases

• Bash Hash Table

• Job States

Page 2: Licão 07 operating the shell

Bash Keywords

A keyword is a word or symbol that has a special meaning to a computer language.

The following symbols and words have special meanings to Bash when they are unquoted and the first word of a command.

! esac select }case fi then [[do for until ]]done function whileelif if timeelse in {

Unlike most computer languages, Bash allows keywords to be used as variable names even though this can make scripts difficult to read.

keep scripts understandable, keywords should not be used for variable names.

Page 3: Licão 07 operating the shell

Use the shell with files and directories

Page 4: Licão 07 operating the shell

Directory Operations

Page 5: Licão 07 operating the shell

The pwd Command

Page 6: Licão 07 operating the shell

The ls Command

Page 7: Licão 07 operating the shell

Long List Option

Page 8: Licão 07 operating the shell

Directory Structure Recursive List

Page 9: Licão 07 operating the shell

The mkdir Command

Page 10: Licão 07 operating the shell

The cd Command

Page 11: Licão 07 operating the shell

The rmdir Command

Page 12: Licão 07 operating the shell

Regular File Utilities

Page 13: Licão 07 operating the shell

The more Command

Page 14: Licão 07 operating the shell

Operations Common to Directories and Files

Page 15: Licão 07 operating the shell

The cp Command

Page 16: Licão 07 operating the shell

Simple File Copy

Page 17: Licão 07 operating the shell

Copy File to A Directory From Home

Page 18: Licão 07 operating the shell

Copy and Rename File

Page 19: Licão 07 operating the shell

Recursive Copy

Page 20: Licão 07 operating the shell

Recursive Copy with Subdirectories

Page 21: Licão 07 operating the shell

Wildcard Copies

Page 22: Licão 07 operating the shell

The mv Command

Page 23: Licão 07 operating the shell

Move File

Page 24: Licão 07 operating the shell

The ln Command

Page 25: Licão 07 operating the shell

The rm Command

Page 26: Licão 07 operating the shell

The find Command

Page 27: Licão 07 operating the shell

Commands

Command-Line Editing

multiple commands

Page 28: Licão 07 operating the shell

Command-Line Editing

There are special key combinations to edit what you type or to repeat commands.

Bash has two editing modes.These modes emulate the keys used in two Linux text editors.

Vi mode mimics the vi and vim editors. Emacs mode works like emacs, nano or pico.

The current editing mode can be checked with the shopt command. shopt -o emacs in emacs mode. shopt -o vi in vi mode.

Only one mode can be on at a time.

$ shopt -o emacsemacs on

$ shopt -o vivi off

Page 29: Licão 07 operating the shell

Command-Line Editing

Regardless of the mode, the arrow keys move the cursor and step through the most recently executed command:

Left arrow—Moves back one character to the left. No characters are erased.Right arrow—Moves forward one character to the right.Up arrow—Moves to the previous command in the command history.Down arrow—Moves to the next command in the command history (if any).

Emacs mode is the default mode on all the major Linux distributions.

The most common emacs keys are:

control-b—Moves back one character to the left. No characters are erased.control-f—Moves forward one character to the right.control-p—Moves to the previous command in the command history.control-n—Moves to the next command in the command history (if any).Tab key—Finds a matching filename and completes it if there is one exact match.

Page 30: Licão 07 operating the shell

Command-Line Editing

complete list of key combinations (or bindings) listed in the Bash man page Readline section.The default key combinations can be changed, listed, or reassigned using the bind command.

Other editing keys are controlled by the older Linux stty (set teletype) command.Running stty shows common command keys and information about your session. Use the -a (all) switch for all settings.

$ sttyspeed 9600 baud; evenp hupclintr = ^C; erase = ^?; kill = ^X;eol2 = ^@; swtch = ^@;susp = ^Z; dsusp = ^Y;werase = ^W; lnext = ^@;-inpck -istrip icrnl -ixany ixoff onlcr-iexten echo echoe echok-echoctl -echoke

Many settings are used only when working with serial port devices and can be ignored. The other settings are control key combinations marked with a caret (^) symbol. Keys with ^@ (or ASCII 0) are not defined.

To change the suspend character to control-v, type$ stty susp ‘^v’

Page 31: Licão 07 operating the shell

Command-Line Editing

key combinations marked with a caret (^) symbol.

erase (usually ^?, which is the backspace key on IBM-style keyboards)

—Moves left and erases one character.

intr (usually ^C)

—Interrupts/stops the current program or cancels the current line.

kill (usually ^X)

—Erases the current line.

rprnt (usually ^R)

—Redraws the current line.

stop (usually ^S)

—Pauses the program so you can read the results on the screen.

start (usually ^Q)

—Resumes the program.

susp (usually ^Z)

—Suspends the current program.

werase (usually ^W)

—Erases the last word typed.

Page 32: Licão 07 operating the shell

Variable Assignments and Displaying Messages

Variables can be created and assigned text using an equals sign. Surround the text with double quotes.

$ FILENAME=”info.txt”

The value of variables can be printed using the printf command. printf has two arguments: a formatting code, and the variable to display.

For simple variables, the formatting code is “%s\n” and the variable name should appear in double quotes with a dollar sign in front of the name:$ printf “%s\n” “$FILENAME”info.txt

printf can also display simple messages.

Put the message in the place of the formatting code:$ printf “Bash is a great shell.\n”Bash is a great shell.

Page 33: Licão 07 operating the shell

Multiple Commands - printf

printf is very similar to the C standard I/O printf() function, but they are not identical. In particular, single- and double-quoted strings are treated differently in shell scripts than in C programs.

first parameter is a format string describing how the items being printed will be represented. For example, “%d” represents an integer number, and code “%f” represents a floating-point number.

$ printf “%d\n” 55$ printf “%f\n” 55.000000

• Include a format code for each item you want to print. • Each format code is replaced with the appropriate value when printed.• Any characters in format string not part of formatting instruction are treated as printable

characters.

$ printf “There are %d customers with purchases over %d.\n” 50 20000There are 50 customers with purchases over 20000.

Page 34: Licão 07 operating the shell

Multiple Commands - printf

The format codes include:%a —Represent a floating-point number in hexadecimal format, using lowercase letters

%A —Represent a floating point number in hexadecimal format, using uppercase letters

%b —Expand backslash sequences

%c —Represent a single character

%d —Display a signed number

%e —Display a floating-point number, shown in exponential (also called “scientific”) notation

%f (or %F) —Display a floating-point number without exponential notation

%g —(General) Let Bash choose %e or %f, depending on the value

%i —Same as %d

%0 —Display an octal number

%q —Quote a string so it can be read properly by a shell script

%s —Display an unquoted string

%u —Display an unsigned number

%x —Display an unsigned hexadecimal number, using lowercase letters

%X —Display an unsigned hexadecimal number, using uppercase letters%% —Display a percent sign

Page 35: Licão 07 operating the shell

Multiple Commands - printf

formatting codes for the representation of unprintable characters.:

\b —Backspace

\f —Form feed (that is, eject a page on a printer)

\n —Start a new line

\r —Carriage return

\t —Tab

\v —Vertical tab

\’ —Single quote character (for compatibility with C)

\\ —Backslash

\0n —n is an octal number representing an 8-bit ASCII character

$ printf “Two separate\nlines\n”Two separateLines

Any 8-bit byte or ASCII character can be represented by \0 or \ and its octal value.$ printf “ASCII 65 (octal 101) is the character \0101\n”ASCII 65 (octal 101) is the character A

Page 36: Licão 07 operating the shell

Variable Assignments and Displaying Messages - printf

printf and variables play an important role in shell scripting

The results of a command can be assigned to a variable using backquotes.

$ DATE=`date`$ printf “%s\n” “$DATE”Wed Feb 13 15:36:41 EST 2012

The date shown is the date when the variable DATE is assigned its value.The value of the variable remains the same until a new value is assigned.

$ printf “%s\n” “$DATE”Wed Feb 13 15:36:41 EST 2012$ DATE=`date`$ printf “%s\n” “$DATE”Wed Feb 13 15:36:48 EST 2012

Page 37: Licão 07 operating the shell

Multiple Commands - printf

Multiple commands can be combined on a single line. How they are executed depends on what symbols separate them.

If each command is separated by a semicolon (;)the commands are executed consecutively, one after another.

$ printf “%s\n” “This is executed” ; printf “%s\n” “And so is this”This is executedAnd so is this

If each command is separated by a double ampersand (&&)the commands are executed until one of them fails or until all the commands are executed.

$ date && printf “%s\n” “The date command was successful”Wed Aug 15 14:36:32 EDT 2012The date command was successful

If each command is separated by a double vertical bar (||) the commands are executed as long as each one fails until all the commands are executed.

$ date ‘duck!’ || printf “%s\n” “The date command failed”date: bad conversionThe date command failed

Page 38: Licão 07 operating the shell

Multiple Commands - printf

Semicolons, double ampersands, and double vertical bars can be mixed in a single line.

$ date ‘format-this!’ || printf “%s\n” “The date command failed” && \printf “%s\n” “But the printf didn’t!”date: bad conversionThe date command failedBut the printf didn’t!

These are primarily intended as command-line shortcuts.When mixed with redirection operators such as >, a long command chain is difficult to read and should be avoided in scripts.

Page 39: Licão 07 operating the shell

Command History

Bash keeps a list of the most recently typed commands. This list is the command history.

The easiest way to browse the command history is with the Up and Down arrow keys

The history can also be searched with an exclamation mark (!).This denotes the start of a command name to be completed by Bash. Bash executes the most recent command that matches. Example:

$ dateWed Apr 4 11:55:58 EDT 2012$ !dWed Apr 4 11:55:58 EDT 2012

If there is no matching command, Bash replies with an event not found error message.$ !xbash: !x: event not found

double ! repeats the last command.$ dateThu Jul 5 14:03:25 EDT 2012$ !!dateThu Jul 5 14:03:28 EDT 2012

Page 40: Licão 07 operating the shell

Command History

There are many variations of the ! command to provide shortcuts in specific situations.

A negative number indicates the relative line number.That is, it indicates number of commands to move back in the history to find one to execute. !! is the same as !-1.

$ dateThu Jul 5 14:04:54 EDT 2012

$ printf “%s\n” $PWD/home/bartsimpson/

$ !-2dateThu Jul 5 14:05:15 EDT 2012

The !# repeats the content of the current command line. (Don’t confuse this with #! in shell scripts.) Use this to run a set of commands twice.

$ date ; sleep 5 ; !#date ; sleep 5 ; date ; sleep 5 ;Fri Jan 18 15:26:54 EST 2012Fri Jan 18 15:26:59 EST 2012

Page 41: Licão 07 operating the shell

Directory Commands - pwd

built-in pwd (present working directory) returns the name of current directory.$ pwd/home/bartsimpson

built-in cd (change directory) command changes your current directory. .. represents the parent directory, . represents the current directory.

$ pwd/home/bartsimpson$ cd .$ pwd/home/bartsimpson$ cd ..$ pwd/home$ cd bartsimpson$ pwd/home/bartsimpson

Page 42: Licão 07 operating the shell

Directory Commands - pwd

Each time you change the directory, Bash updates the variable PWD containing thepath to your current working directory.

Bash also maintains a second variable called OLDPWD that contains the last directory you were in.

Using minus sign (–) with cd, you can switch between the current directory and last directory. This is a useful shortcut to work in two different directories.

$ pwd/home/kburtch$ cd ..$ pwd/home$ cd -$ pwd/home/kburtch$ cd -$ pwd/home

Page 43: Licão 07 operating the shell

Directory Commands

The tilde (~) represents your current directory. Use it to move to a directory relative to your home directory.

To move to a directory called mail in your home directory, type

$ cd ~/mail

Page 44: Licão 07 operating the shell

Specialized Navigation and History

built-in dirs command shows the list of saved directories.The current directory is always the first item in the list.

$ dirs~

built-in pushd (push directory) command adds (or pushes) directories onto list and changes the current directory to the new directory.

$ pushd /home/bartsimpon/invoices~/invoices ~$ pushd /home/bartsimpon/work~/work ~/invoices ~$ pwd/home/bartsimpson/work

There are now three directories in the list.dirs -l switch displays the directory names without any short forms.-n (no change) switch will put a directory into the list without changing directories.-N (rotate Nth) moves the nth directory from the left (or, with +N, from the right) to the top of the list.

$ dirs -l/home/bartsimpson/work /home/bartsimpson/invoices /home/bartsimpson

Page 45: Licão 07 operating the shell

Specialized Navigation and History

built-in popd (pop directory) command is the opposite of the pushd.

popd discards the first directory and moves to the next directory in the list.

$ popd~/invoices ~$ pwd/home/bartsimpson/invoices

The switches for popd are similar to pushd: -n to pop without moving, -N to delete the Nth entry from the left (or, with +N, the right).

Page 46: Licão 07 operating the shell

Colon Command

The simplest shell command is the colon (:).This is the colon command (called “no-op” or “null command”) and does nothing.

There are some places in shell programs where a statement is required. In those cases, you can use : to indicate nothing special should be done.At the command prompt, : has no effect.

$ :$

The colon command can have parameters and file redirections.This can have strange effects, such as running the date command using backquotes, giving the

results to the null command that quietly discards them.

$ : `date`$

This has the same effect as redirecting the output of date to the /dev/null file.$ date > /dev/null

Page 47: Licão 07 operating the shell

Shell Aliases

An alias is a short form of a command.built-in alias command creates simple abbreviations for current Bash session.

To create an alias, use the alias command to assign a command and its switches a name.

$ alias lf=’ls -qFl’$ lf-rw-r----- 1 bartsimpson devgroup 10809 Apr 6 11:00 assets.txt-rw-r----- 1 bartsimposn devgroup 4713 Mar 9 2012 mailing_list.txt

Typing the alias command by itself, or with -p switch, lists the current aliases.

$ aliasalias lf=’ls -qFl’

Bash interprets an alias only once, allowing the aliasing of a command with its own name.

$ alias ls=’ls -qF’ # Bash isn’t confused

There is no method for giving arguments to an alias. If arguments are needed, define a more powerful shell function instead.

built-in unalias command removes an alias. Use the -a switch to remove them all.

Page 48: Licão 07 operating the shell

Bash Hash Table

built-in hash command maintains the hash table.

Without any switches, hash lists the memorized commands, where they are, and the number of times the command has been executed during this session.

$ hashhits command1 /bin/ls1 /bin/uname1 /usr/bin/tput1 /bin/stty1 /usr/bin/uptime1 /usr/bin/man

When a command is specified, Bash searches for the new location of the command. For example, if you create your own ls command in your current directory, and the PATH variable gives precedence to files in your current directory, the hash ls command finds your ls command first, replacing /bin/ls with ./ls.

Page 49: Licão 07 operating the shell

Job States

Page 50: Licão 07 operating the shell

Job Control

Job control - Ability to selectively suspend execution of processes and continue their execution later.

A job is a process or a pipeline of processes that were started by the shell.

job which receives keyboard input is called the foreground job.

•When a foreground process is running, it receives keyboard input and signals.• Processes started are run in foreground by default and continue until they exit.

To run a process in background – input command followed by special character &

• Processes running in the background may still send output to the terminal.• They do not receive keyboard input unless they are brought to the foreground.

When bash starts a background job, it prints a line with: - job number and - process ID of last process in pipeline

Page 51: Licão 07 operating the shell

Job Control

command jobs displays current list of jobs either running or stopped.

foo:~ $ dd if=/dev/zero of=/dev/null bs=1 &[1] 1181foo:~ $ cat /dev/urandom | grep hello &[2] 1183foo:~ $ jobs[1]- Running dd if=/dev/zero of=/dev/null bs=1 &[2]+ Running cat /dev/urandom | grep hello &

Page 52: Licão 07 operating the shell

Job Control

key sequences entered to foreground processes:

Key Signal Meaning Usage

Ctrl+C SIGINT Interrupt Interrupt the program running in the foreground

Ctrl+Z SIGSTOP Suspend Suspend the program running in the foreground

cmds entered to control background processes.

Command Meaning Usage

fg foreground Run the background job in the foreground. If it has suspended, restart it.

bg background Restart a suspended job.

fg makes most recently executed job a foreground job. You can specify a specific job number. (Ex. fg 2 will make job 2 run in the foreground)

bg makes most recently executed job continue to run in background.You can make a specific job run in the background by specifying a job number (Ex. bg 2)

Page 53: Licão 07 operating the shell

Job Control

kill commandkill job based on job number (instead of PID) using percentage sign to specify the job number

foo:~ $ jobs[1]- Running dd if=/dev/zero of=/dev/null bs=1 &[2]+ Running cat /dev/urandom | grep hello &foo:~ $ kill %1foo:~ $[1]- Terminated dd if=/dev/zero of=/dev/null bs=1foo:~ $ jobs[2]+ Running cat /dev/urandom | grep hello &foo:~ $ kill %2foo:~ $[2]+ Terminated cat /dev/urandom | grep hello

Page 54: Licão 07 operating the shell

Job Control

ps – process status

options supported by ps are somewhat complex.

GNU version supports: Unix98 options (letters); BSD options (dash); GNU options (two dashes).

To ... Unix98 BSD

- Show all processes ps -ax ps -A ps -e

- Show full info ps -u (user format) ps -f (full listing)

- Show full info for all processes ps -aux ps -ef ps -Af

foo:~ $ ps -fUID PID PPID C STIME TTY TIME CMDgeorgem 987 612 0 20:32 pts/2 00:00:00 /bin/bashgeorgem 3398 987 0 21:11 pts/2 00:00:00 ps -f

foo:~ $ ps uUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDgeorgem 987 0.0 1.7 4676 2040 pts/2 S 20:32 0:00 /bin/bashgeorgem 3399 0.0 0.5 2524 696 pts/2 R 21:11 0:00 ps u

ps -w – display in wide format

ps -f – display in forest of processes, similar to output of pstree - hierarchical view

Page 55: Licão 07 operating the shell

Job Control

top – displays processes that use up the most CPU or memory.