Capitulo 7 Reading and Writing Test Form a

#

Comments. Lines commencement with a # (with the exception of #!) are comments and will not be executed.

# This line is a comment.

Comments may also occur following the terminate of a command.

echo "A comment volition follow." # Comment here. #                            ^ Note whitespace before #

Comments may besides follow whitespace at the beginning of a line.

                  # A tab precedes this comment.

Comments may even be embedded within a pipe.

initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\due north' |\ # Delete lines containing '#' comment graphic symbol.            sed -eastward 's/\./\. /g' -eastward 's/_/_ /g'` ) # Excerpted from life.sh script

Caution

A control may not follow a comment on the same line. There is no method of terminating the comment, in order for "live code" to begin on the aforementioned line. Use a new line for the next command.

Note

Of course, a quoted or an escaped # in an repeat argument does not begin a comment. Also, a # appears in certain parameter-substitution constructs and in numerical constant expressions.

echo "The # here does non begin a comment." echo 'The # here does not begin a comment.' echo The \# here does not begin a comment. echo The # here begins a annotate.  echo ${PATH#*:}       # Parameter substitution, not a comment. echo $(( 2#101011 ))  # Base of operations conversion, not a comment.  # Thanks, Southward.C.

The standard quoting and escape characters (" ' \) escape the #.

Certain pattern matching operations besides use the #.

;

Control separator [semicolon]. Permits putting ii or more commands on the aforementioned line.

repeat hi; echo there   if [ -x "$filename" ]; then    #  Note the space after the semicolon. #+                   ^^   echo "File $filename exists."; cp $filename $filename.bak else   #                       ^^   echo "File $filename not plant."; touch $filename fi; echo "File examination consummate."

Annotation that the ";" sometimes needs to be escaped.

;;

Terminator in a case option [double semicolon].

case "$variable" in   abc)  echo "\$variable = abc" ;;   xyz)  echo "\$variable = xyz" ;; esac

;;&, ;&
.
.

"dot", every bit a component of a filename. When working with filenames, a leading dot is the prefix of a "hidden" file, a file that an ls volition not commonly show.

                  bash$                                                        touch .hidden-file                                    bash$                                                        ls -l                                    total 10  -rw-r--r--    1 bozo      4034 Jul 18 22:04 data1.addressbook  -rw-r--r--    i bozo      4602 May 25 thirteen:58 data1.addressbook.bak  -rw-r--r--    1 bozo       877 Dec 17  2000 employment.addressbook                  bash$                                                        ls -al                                    total 14  drwxrwxr-x    2 bozo  bozo      1024 Aug 29 twenty:54 ./  drwx------   52 bozo  bozo      3072 Aug 29 xx:51 ../  -rw-r--r--    1 bozo  bozo      4034 Jul eighteen 22:04 data1.addressbook  -rw-r--r--    1 bozo  bozo      4602 May 25 xiii:58 data1.addressbook.bak  -rw-r--r--    1 bozo  bozo       877 Dec 17  2000 employment.addressbook  -rw-rw-r--    1 bozo  bozo         0 Aug 29 20:54 .hidden-file                

When because directory names, a single dot represents the current working directory, and two dots denote the parent directory.

                  bash$                                                        pwd                                    /home/bozo/projects                  bash$                                                        cd .                                    bash$                                                        pwd                                    /habitation/bozo/projects                  bash$                                                        cd ..                                    bash$                                                        pwd                                    /home/bozo/                

The dot often appears as the destination (directory) of a file movement command, in this context meaning current directory.

                  bash$                                                        cp /domicile/bozo/current_work/junk/* .                                  

Copy all the "junk" files to $PWD.

.
"

fractional quoting [double quote]. "STRING" preserves (from interpretation) most of the special characters within STRING. See Affiliate v.

'

full quoting [single quote]. 'STRING' preserves all special characters within STRING. This is a stronger form of quoting than "STRING". Run into Chapter v.

,

comma operator. The comma operator [1] links together a series of arithmetics operations. All are evaluated, but only the terminal i is returned.

let "t2 = ((a = 9, 15 / iii))" # Set "a = 9" and "t2 = 15 / three"

The comma operator can also concatenate strings.

for file in /{,usr/}bin/*calc #             ^    Find all executable files ending in "calc" #+                 in /bin and /usr/bin directories. practise         if [ -ten "$file" ]         so           echo $file         fi washed  # /bin/ipcalc # /usr/bin/kcalc # /usr/bin/oidcalc # /usr/bin/oocalc   # Thank you, Rory Winston, for pointing this out.

,, ,
\

escape [backslash]. A quoting mechanism for unmarried characters.

\Ten escapes the character X. This has the result of "quoting" X, equivalent to 'X'. The \ may be used to quote " and ', and so they are expressed literally.

Run across Affiliate five for an in-depth explanation of escaped characters.

/

Filename path separator [frontward slash]. Separates the components of a filename (as in /home/bozo/projects/Makefile).

This is besides the segmentation arithmetic operator.

`

command substitution. The `command` construct makes available the output of command for consignment to a variable. This is also known as backquotes or backticks.

:

null command [colon]. This is the shell equivalent of a "NOP" ( no op , a do-nix functioning). It may be considered a synonym for the shell builtin true. The ":" control is itself a Bash builtin, and its exit status is true (0).

Endless loop:

while : do    operation-1    operation-2    ...    operation-n done  # Same as: #    while true #    do #      ... #    done

Placeholder in if/then exam:

if condition then :   # Do zilch and branch ahead else     # Or else ...    take-some-action fi

Provide a placeholder where a binary performance is expected, see Example viii-2 and default parameters.

: ${username=`whoami`} # ${username=`whoami`}   Gives an error without the leading : #                        unless "username" is a command or builtin...  : ${1?"Usage: $0 ARGUMENT"}     # From "usage-message.sh example script.

Provide a placeholder where a control is expected in a here certificate. Come across Example 19-x.

Evaluate string of variables using parameter exchange (every bit in Example 10-7).

: ${HOSTNAME?} ${USER?} ${Mail?} #  Prints error bulletin #+ if one or more than of essential environmental variables not set.

Variable expansion / substring replacement.

In combination with the > redirection operator, truncates a file to aught length, without changing its permissions. If the file did not previously exist, creates it.

: > data.xxx   # File "data.thirty" now empty.	        # Aforementioned effect as   cat /dev/goose egg >data.xxx # However, this does not fork a new process, since ":" is a builtin.

Meet also Example 16-xv.

In combination with the >> redirection operator, has no effect on a pre-existing target file ( : >> target_file ). If the file did not previously exist, creates information technology.

Note

This applies to regular files, not pipes, symlinks, and certain special files.

May be used to begin a comment line, although this is not recommended. Using # for a comment turns off error checking for the remainder of that line, then almost anything may appear in a comment. However, this is not the case with :.

: This is a comment that generates an error, ( if [ $ten -eq 3] ).

The ":" serves as a field separator, in /etc/passwd, and in the $PATH variable.

                  bash$                                                        repeat $PATH                                    /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/sbin:/usr/sbin:/usr/games                

A colon is adequate equally a function proper name.

:() {   echo "The proper noun of this office is "$FUNCNAME" "   # Why use a colon equally a role name?   # It's a style of obfuscating your code. }  :  # The proper noun of this function is :

This is non portable beliefs, and therefore not a recommended do. In fact, more than recent releases of Fustigate practice not let this usage. An underscore _ works, though.

A colon can serve as a placeholder in an otherwise empty function.

not_empty () {   : } # Contains a : (naught command), and so is not empty.

!

reverse (or negate) the sense of a examination or exit status [bang]. The ! operator inverts the exit status of the control to which it is practical (run across Example 6-two). It too inverts the meaning of a test operator. This can, for instance, change the sense of equal ( = ) to not-equal ( != ). The ! operator is a Bash keyword.

In a different context, the ! as well appears in indirect variable references.

In withal another context, from the command line, the ! invokes the Fustigate history mechanism (see Appendix 50). Note that within a script, the history mechanism is disabled.

*

wild card [asterisk]. The * character serves as a "wild card" for filename expansion in globbing. By itself, it matches every filename in a given directory.

                  bash$                                                        echo *                                    abs-book.sgml add-drive.sh agram.sh alias.sh                

The * also represents any number (or zero) characters in a regular expression.

*

arithmetic operator. In the context of arithmetic operations, the * denotes multiplication.

** A double asterisk tin correspond the exponentiation operator or extended file-match globbing.

?

test operator. Within certain expressions, the ? indicates a test for a condition.

In a double-parentheses construct, the ? can serve as an element of a C-style trinary operator. [two]

condition ? upshot-if-true : upshot-if-false

(( var0 = var1<98?9:21 )) #                ^ ^  # if [ "$var1" -lt 98 ] # so #   var0=9 # else #   var0=21 # fi

In a parameter substitution expression, the ? tests whether a variable has been set.

?
$

Variable substitution (contents of a variable).

var1=v var2=23skidoo  repeat $var1     # five repeat $var2     # 23skidoo

A $ prefixing a variable name indicates the value the variable holds.

$
${}
$' ... '

Quoted string expansion. This construct expands single or multiple escaped octal or hex values into ASCII [3] or Unicode characters.

$*, $@
$?
$$

procedure ID variable. The $$ variable holds the procedure ID [4] of the script in which information technology appears.

()

control group.

Important

A list of commands within parentheses starts a subshell.

Variables inside parentheses, within the subshell, are not visible to the balance of the script. The parent procedure, the script, cannot read variables created in the child process, the subshell.

a=123 ( a=321; )	        echo "a = $a"   # a = 123 # "a" within parentheses acts like a local variable.

assortment initialization.

Array=(element1 element2 element3)

{xxx,yyy,zzz,...}

Caryatid expansion.

echo \"{These,words,are,quoted}\"   # " prefix and suffix # "These" "words" "are" "quoted"   true cat {file1,file2,file3} > combined_file # Concatenates the files file1, file2, and file3 into combined_file.  cp file22.{txt,backup} # Copies "file22.txt" to "file22.backup"

A command may act upon a comma-separated listing of file specs within braces . [five] Filename expansion (globbing) applies to the file specs between the braces.

Caution

No spaces allowed within the braces unless the spaces are quoted or escaped.

echo {file1,file2}\ :{\ A," B",' C'}

file1 : A file1 : B file1 : C file2 : A file2 : B file2 : C

{a..z}

Extended Brace expansion.

echo {a..z} # a b c d e f thou h i j g 50 1000 due north o p q r south t u v w x y z # Echoes characters between a and z.  echo {0..3} # 0 ane 2 iii # Echoes characters betwixt 0 and 3.   base64_charset=( {A..Z} {a..z} {0..nine} + / = ) # Initializing an array, using extended caryatid expansion. # From vladz'southward "base64.sh" example script.

The {a..z} extended caryatid expansion structure is a characteristic introduced in version 3 of Bash.

{}

Block of code [curly brackets]. Likewise referred to as an inline group, this construct, in issue, creates an anonymous office (a part without a name). Notwithstanding, unlike in a "standard" function, the variables inside a code block remain visible to the balance of the script.

                  bash$                                                        { local a; 	      a=123; }                                    bash: local: tin simply be used in a function                

a=123 { a=321; } echo "a = $a"   # a = 321   (value inside code block)  # Thanks, Southward.C.

The lawmaking block enclosed in braces may accept I/O redirected to and from it.

Example three-one. Lawmaking blocks and I/O redirection

#!/bin/bash # Reading lines in /etc/fstab.  File=/etc/fstab  { read line1 read line2 } < $File  repeat "Get-go line in $File is:" echo "$line1" repeat echo "Second line in $File is:" echo "$line2"  leave 0  # At present, how do you parse the separate fields of each line? # Hint: apply awk, or . . . # . . . Hans-Joerg Diers suggests using the "set" Bash builtin.

Example three-2. Saving the output of a code block to a file

#!/bin/bash # rpm-check.sh  #  Queries an rpm file for description, list, #+ and whether it can be installed. #  Saves output to a file. #  #  This script illustrates using a code block.  SUCCESS=0 E_NOARGS=65  if [ -z "$one" ] then   echo "Usage: `basename $0` rpm-file"   exit $E_NOARGS fi    { # Begin lawmaking block.   echo   echo "Archive Description:"   rpm -qpi $1       # Query description.   echo   repeat "Archive Listing:"   rpm -qpl $1       # Query list.   repeat   rpm -i --exam $1  # Query whether rpm file tin can be installed.   if [ "$?" -eq $SUCCESS ]   and so     repeat "$one can be installed."   else     echo "$1 cannot be installed."   fi     echo              # Finish code block. } > "$1.test"       # Redirects output of everything in block to file.  echo "Results of rpm test in file $i.test"  # Run into rpm man page for explanation of options.  exit 0

Note

Unlike a command grouping within (parentheses), as higher up, a code block enclosed past {braces} volition non commonly launch a subshell. [six]

It is possible to iterate a code block using a not-standard for-loop.

{}

placeholder for text. Used subsequently xargs -i (supplant strings selection). The {} double curly brackets are a placeholder for output text.

ls . | xargs -i -t cp ./{} $1 #            ^^         ^^  # From "ex42.sh" (copydir.sh) example.

{} \;

pathname. Mostly used in find constructs. This is not a trounce builtin.

Note

The ";" ends the -exec pick of a detect command sequence. Information technology needs to be escaped to protect information technology from interpretation past the shell.

[ ]

test.

Test expression between [ ]. Notation that [ is part of the shell builtin test (and a synonym for it), not a link to the external command /usr/bin/exam.

[[ ]]

test.

Test expression betwixt [[ ]]. More flexible than the single-bracket [ ] test, this is a shell keyword.

See the word on the [[ ... ]] construct.

[ ]

array element.

In the context of an array, brackets set off the numbering of each element of that array.

Array[1]=slot_1 echo ${Array[ane]}

[ ]

range of characters.

As part of a regular expression, brackets delineate a range of characters to friction match.

$[ ... ]

integer expansion.

Evaluate integer expression between $[ ].

a=3 b=seven  echo $[$a+$b]   # 10 echo $[$a*$b]   # 21

Note that this usage is deprecated, and has been replaced by the (( ... )) construct.

(( ))

integer expansion.

Expand and evaluate integer expression between (( )).

Encounter the discussion on the (( ... )) construct.

> &> >& >> < <>

scriptname >filename redirects the output of scriptname to file filename. Overwrite filename if it already exists.

command &>filename redirects both the stdout and the stderr of command to filename.

Note

This is useful for suppressing output when testing for a condition. For example, let united states of america test whether a certain control exists.

                            bash$                                                                                      type bogus_command &>/dev/null                                                                                    bash$                                                                                      echo $?                                                        1                          

Or in a script:

command_test () { blazon "$one" &>/dev/null; } #                                      ^  cmd=rmdir            # Legitimate command. command_test $cmd; echo $?   # 0   cmd=bogus_command    # Illegitimate command command_test $cmd; echo $?   # i

command >&2 redirects stdout of command to stderr.

scriptname >>filename appends the output of scriptname to file filename. If filename does not already exist, information technology is created.

[i]<>filename opens file filename for reading and writing, and assigns file descriptor i to it. If filename does not be, it is created.

(command)>

<(command)

In a different context, the "<" and ">" characters human activity as string comparison operators.

In notwithstanding another context, the "<" and ">" characters act equally integer comparison operators. See also Example 16-9.

<<
<<<
<, >

ASCII comparison.

veg1=carrots veg2=tomatoes  if [[ "$veg1" < "$veg2" ]] then   echo "Although $veg1 precede $veg2 in the dictionary,"   echo -north "this does not necessarily imply anything "   echo "about my culinary preferences." else   echo "What kind of dictionary are you using, anyhow?" fi

\<, \>

bash$ grep '\<the\>' textfile

|

pipe. Passes the output (stdout) of a previous command to the input (stdin) of the next 1, or to the shell. This is a method of chaining commands together.

echo ls -fifty | sh #  Passes the output of "echo ls -l" to the vanquish, #+ with the same issue as a simple "ls -l".   cat *.lst | sort | uniq # Merges and sorts all ".lst" files, then deletes duplicate lines.

The output of a command or commands may be piped to a script.

#!/bin/bash # uppercase.sh : Changes input to upper-case letter.  tr 'a-z' 'A-Z' #  Alphabetic character ranges must be quoted #+ to forbid filename generation from single-alphabetic character filenames.  go out 0

Now, permit us pipe the output of ls -l to this script.

                  fustigate$                                                        ls -l | ./upper-case letter.sh                                    -RW-RW-R--    1 BOZO  BOZO       109 Apr  7 19:49 1.TXT  -RW-RW-R--    1 BOZO  BOZO       109 APR 14 16:48 2.TXT  -RW-R--R--    1 BOZO  BOZO       725 April 20 twenty:56 Information-FILE                

Note

The stdout of each process in a pipe must be read every bit the stdin of the side by side. If this is not the case, the data stream volition cake, and the pipe will not behave as expected.

true cat file1 file2 | ls -l | sort # The output from "true cat file1 file2" disappears.

A pipe runs as a child process, and therefore cannot change script variables.

variable="initial_value" echo "new_value" | read variable repeat "variable = $variable"     # variable = initial_value

If one of the commands in the pipe aborts, this prematurely terminates execution of the pipe. Called a broken pipage, this condition sends a SIGPIPE signal.

>|

force redirection (fifty-fifty if the noclobber option is set up). This will forcibly overwrite an existing file.

||

OR logical operator. In a test construct, the || operator causes a return of 0 (success) if either of the linked examination conditions is truthful.

&

Run job in groundwork. A control followed past an & will run in the groundwork.

                  bash$                                                        sleep 10 &                                    [one] 850                  [one]+  Done                    sleep 10                

Within a script, commands and even loops may run in the background.

Instance 3-iii. Running a loop in the background

#!/bin/bash # groundwork-loop.sh  for i in 1 2 3 4 5 6 seven eight ix x            # Showtime loop. do   echo -north "$i " washed & # Run this loop in background.        # Will sometimes execute after second loop.  echo   # This 'echo' sometimes will non display.  for i in 11 12 thirteen 14 15 16 17 xviii xix 20   # Second loop. do   echo -n "$i " done    repeat   # This 'echo' sometimes will not brandish.  # ======================================================  # The expected output from the script: # i two 3 4 5 6 7 8 9 10  # 11 12 13 14 15 sixteen 17 18 nineteen 20   # Sometimes, though, you get: # 11 12 13 14 xv 16 17 eighteen 19 20  # 1 two 3 4 5 six 7 8 nine 10 bozo $ # (The second 'repeat' doesn't execute. Why?)  # Occasionally as well: # 1 two 3 4 five 6 7 viii 9 x eleven 12 13 fourteen 15 16 17 eighteen nineteen 20 # (The first 'echo' doesn't execute. Why?)  # Very rarely something like: # eleven 12 thirteen 1 ii 3 four v vi vii 8 9 10 fourteen 15 16 17 18 19 twenty  # The foreground loop preempts the groundwork one.  leave 0  #  Nasimuddin Ansari suggests calculation    sleep 1 #+ after the   repeat -due north "$i"   in lines 6 and 14, #+ for some existent fun.

Caution

A command run in the background inside a script may cause the script to hang, waiting for a keystroke. Fortunately, there is a remedy for this.

&&

AND logical operator. In a test construct, the && operator causes a return of 0 (success) only if both the linked test conditions are true.

-

COMMAND -[Option1][Option2][...]

ls -al

sort -dfu $filename

if [ $file1 -ot $file2 ] then #      ^   repeat "File $file1 is older than $file2." fi  if [ "$a" -eq "$b" ] then #    ^   echo "$a is equal to $b." fi  if [ "$c" -eq 24 -a "$d" -eq 47 ] then #    ^              ^   echo "$c equals 24 and $d equals 47." fi   param2=${param1:-$DEFAULTVAL} #               ^

--

The double-dash -- prefixes long (verbatim) options to commands.

sort --ignore-leading-blanks

Used with a Bash builtin, it means the terminate of options to that detail control.

Tip

This provides a handy means of removing files whose names begin with a nuance.

                            fustigate$                                                                                      ls -l                                                        -rw-r--r-- 1 bozo bozo 0 Nov 25 12:29 -badname                            bash$                                                                                      rm -- -badname                                                        fustigate$                                                                                      ls -l                                                        total 0                          

The double-nuance is too used in conjunction with gear up.

set -- $variable (as in Example xv-18)

-

redirection from/to stdin or stdout [dash].

                  bash$                                                        true cat -                                                        abc                                    abc                  ...                                      Ctl-D                                  

As expected, true cat - echoes stdin, in this case keyboarded user input, to stdout. Simply, does I/O redirection using - accept real-world applications?

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -) # Move entire file tree from one directory to another # [courtesy Alan Cox <a.cox@swansea.ac.united kingdom of great britain and northern ireland>, with a minor change]  # i) cd /source/directory #    Source directory, where the files to be moved are. # ii) && #   "And-list": if the 'cd' operation successful, #    then execute the next command. # 3) tar cf - . #    The 'c' option 'tar' archiving command creates a new archive, #    the 'f' (file) option, followed by '-' designates the target file #    equally stdout, and practice information technology in current directory tree ('.'). # four) | #    Piped to ... # five) ( ... ) #    a subshell # 6) cd /dest/directory #    Change to the destination directory. # 7) && #   "And-list", equally above # viii) tar xpvf - #    Unarchive ('10'), preserve ownership and file permissions ('p'), #    and transport verbose letters to stdout ('v'), #    reading information from stdin ('f' followed by '-'). # #    Notation that 'ten' is a control, and 'p', '5', 'f' are options. # # Whew!    # More elegant than, only equivalent to: #   cd source/directory #   tar cf - . | (cd ../dest/directory; tar xpvf -) # #     Also having same effect: # cp -a /source/directory/* /dest/directory #     Or: # cp -a /source/directory/* /source/directory/.[^.]* /dest/directory #     If in that location are hidden files in /source/directory.

bunzip2 -c linux-two.6.16.tar.bz2 | tar xvf - #  --uncompress tar file--      | --then laissez passer information technology to "tar"-- #  If "tar" has not been patched to handle "bunzip2", #+ this needs to be done in two discrete steps, using a pipage. #  The purpose of the exercise is to unarchive "bzipped" kernel source.

Note that in this context the "-" is non itself a Fustigate operator, just rather an pick recognized by certain UNIX utilities that write to stdout, such every bit tar, cat, etc.

                  bash$                                                        echo "whatever" | true cat -                                    any                

Where a filename is expected, - redirects output to stdout (sometimes seen with tar cf ), or accepts input from stdin, rather than from a file. This is a method of using a file-oriented utility as a filter in a piping.

                  bash$                                                        file                                    Usage: file [-bciknvzL] [-f namefile] [-yard magicfiles] file...                

Past itself on the command-line, file fails with an error bulletin.

Add a "-" for a more useful result. This causes the shell to expect user input.

                  bash$                                                        file -                                                        abc                                    standard input:              ASCII text                  bash$                                                        file -                                                        #!/bin/bash                                    standard input:              Bourne-Again crush script text executable                

Now the control accepts input from stdin and analyzes information technology.

The "-" can be used to pipage stdout to other commands. This permits such stunts as prepending lines to a file.

Using diff to compare a file with a section of another:

grep Linux file1 | diff file2 -

Finally, a real-world example using - with tar.

Example iii-4. Fill-in of all files changed in last day

#!/bin/bash  #  Backs up all files in current directory modified inside last 24 hours #+ in a "tarball" (tarred and gzipped file).  BACKUPFILE=backup-$(date +%m-%d-%Y) #                 Embeds date in fill-in filename. #                 Thanks, Joshua Tschida, for the idea. annal=${1:-$BACKUPFILE} #  If no fill-in-archive filename specified on command-line, #+ it will default to "fill-in-MM-DD-YYYY.tar.gz."  tar cvf - `find . -mtime -one -type f -print` > $archive.tar gzip $archive.tar repeat "Directory $PWD backed up in archive file \"$archive.tar.gz\"."   #  Stephane Chazelas points out that the above lawmaking will fail #+ if in that location are too many files institute #+ or if whatever filenames comprise blank characters.  # He suggests the following alternatives: # ------------------------------------------------------------------- #   find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$annal.tar" #      using the GNU version of "find".   #   notice . -mtime -i -blazon f -exec tar rvf "$annal.tar" '{}' \; #         portable to other UNIX flavors, merely much slower. # -------------------------------------------------------------------   get out 0

Caution

Filenames beginning with "-" may cause bug when coupled with the "-" redirection operator. A script should check for this and add an appropriate prefix to such filenames, for case ./-FILENAME, $PWD/-FILENAME, or $PATHNAME/-FILENAME.

If the value of a variable begins with a - , this may likewise create problems.

var="-due north" echo $var		 # Has the effect of "echo -north", and outputs nothing.

-

previous working directory. A cd - control changes to the previous working directory. This uses the $OLDPWD environmental variable.

Caution

Do not confuse the "-" used in this sense with the "-" redirection operator only discussed. The interpretation of the "-" depends on the context in which it appears.

-
=

In a different context, the "=" is a string comparison operator.

+

In a different context, the + is a Regular Expression operator.

+

Option. Option flag for a command or filter.

Sure commands and builtins apply the + to enable certain options and the - to disable them. In parameter exchange, the + prefixes an alternating value that a variable expands to.

%

permit "z = 5 % 3" repeat $z  # 2

In a dissimilar context, the % is a pattern matching operator.

~

home directory [tilde]. This corresponds to the $Abode internal variable. ~bozo is bozo's home directory, and ls ~bozo lists the contents of it. ~/ is the current user'southward dwelling directory, and ls ~/ lists the contents of information technology.

                  bash$                                                        repeat ~bozo                                    /dwelling/bozo                  bash$                                                        echo ~                                    /home/bozo                  bash$                                                        echo ~/                                    /home/bozo/                  bash$                                                        repeat ~:                                    /home/bozo:                  fustigate$                                                        repeat ~nonexistent-user                                    ~nonexistent-user                

~+

current working directory. This corresponds to the $PWD internal variable.

~-

previous working directory. This corresponds to the $OLDPWD internal variable.

=~
^
^, ^^
Control Characters

alter the behavior of the terminal or text display. A control character is a Control + primal combination (pressed simultaneously). A control character may as well be written in octal or hexadecimal notation, following an escape.

Command characters are non normally useful inside a script.

  • Ctl-A

    Moves cursor to beginning of line of text (on the control-line).

  • Ctl-B

    Backspace (nondestructive).

  • Ctl-C

    Break . Finish a foreground job.

  • Ctl-D

    Log out from a beat (similar to exit).

    EOF (end-of-file). This likewise terminates input from stdin.

    When typing text on the console or in an xterm window, Ctl-D erases the character under the cursor. When there are no characters present, Ctl-D logs out of the session, as expected. In an xterm window, this has the issue of closing the window.

  • Ctl-E

    Moves cursor to finish of line of text (on the command-line).

  • Ctl-F

    Moves cursor forwards one character position (on the command-line).

  • Ctl-G

    BEL . On some sometime-time teletype terminals, this would actually ring a bell. In an xterm it might beep.

  • Ctl-H

    Rubout (destructive backspace). Erases characters the cursor backs over while backspacing.

    #!/bin/bash # Embedding Ctl-H in a cord.  a="^H^H"                  # Ii Ctl-H'southward -- backspaces                           # ctl-V ctl-H, using vi/vim echo "abcdef"             # abcdef echo echo -north "abcdef$a "       # abcd f #  Space at end  ^              ^  Backspaces twice. echo echo -n "abcdef$a"        # abcdef #  No space at end               ^ Doesn't backspace (why?).                           # Results may not be quite equally expected. echo; echo  # Constantin Hagemeier suggests trying: # a=$'\010\010' # a=$'\b\b' # a=$'\x08\x08' # But, this does not alter the results.  ########################################  # Now, endeavor this.  rubout="^H^H^H^H^H"       # five x Ctl-H.  echo -n "12345678" sleep 2 repeat -due north "$rubout" slumber 2

  • Ctl-I

    Horizontal tab .

  • Ctl-J

    Newline (line feed). In a script, may also exist expressed in octal notation -- '\012' or in hexadecimal -- '\x0a'.

  • Ctl-Thousand

    Vertical tab .

    When typing text on the console or in an xterm window, Ctl-G erases from the character under the cursor to finish of line. Within a script, Ctl-Grand may conduct differently, equally in Lee Lee Maschmeyer'due south example, below.

  • Ctl-L

    Formfeed (clear the last screen). In a terminal, this has the same effect as the articulate command. When sent to a printer, a Ctl-50 causes an advance to end of the paper canvas.

  • Ctl-K

    Carriage return .

    #!/bin/bash # Thanks, Lee Maschmeyer, for this example.  read -n 1 -s -p \ $'Control-M leaves cursor at first of this line. Press Enter. \x0d'            # Of class, '0d' is the hex equivalent of Control-M. echo >&2   #  The '-due south' makes anything typed silent,            #+ and so it is necessary to become to new line explicitly.  read -n 1 -s -p $'Command-J leaves cursor on next line. \x0a'            #  '0a' is the hex equivalent of Control-J, linefeed. echo >&2  ###  read -n 1 -south -p $'And Command-One thousand\x0bgoes straight downwards.' repeat >&2   #  Command-One thousand is vertical tab.  # A better example of the upshot of a vertical tab is:  var=$'\x0aThis is the bottom line\x0bThis is the top line\x0a' echo "$var" #  This works the same mode as the above case. However: echo "$var" | col #  This causes the right cease of the line to be higher than the left end. #  It also explains why we started and ended with a line feed -- #+ to avoid a garbled screen.  # As Lee Maschmeyer explains: # -------------------------- #  In the [commencement vertical tab example] . . . the vertical tab #+ makes the printing go straight down without a carriage return. #  This is true but on devices, such as the Linux console, #+ that can't go "backward." #  The real purpose of VT is to become straight Upward, not down. #  It can be used to print superscripts on a printer. #  The col utility can be used to emulate the proper beliefs of VT.  exit 0

  • Ctl-N

    Erases a line of text recalled from history buffer [viii] (on the command-line).

  • Ctl-O

    Issues a newline (on the command-line).

  • Ctl-P

    Recalls last command from history buffer (on the control-line).

  • Ctl-Q

    Resume ( XON ).

    This resumes stdin in a terminal.

  • Ctl-R

    Backwards search for text in history buffer (on the command-line).

  • Ctl-South

    Suspend ( XOFF ).

    This freezes stdin in a terminal. (Utilise Ctl-Q to restore input.)

  • Ctl-T

    Reverses the position of the character the cursor is on with the previous character (on the command-line).

  • Ctl-U

    Erase a line of input, from the cursor backward to starting time of line. In some settings, Ctl-U erases the entire line of input, regardless of cursor position.

  • Ctl-Five

    When inputting text, Ctl-Five permits inserting control characters. For example, the following ii are equivalent:

    echo -e '\x0a' repeat <Ctl-Five><Ctl-J>

    Ctl-V is primarily useful from within a text editor.

  • Ctl-West

    When typing text on the console or in an xterm window, Ctl-Due west erases from the graphic symbol under the cursor backwards to the first example of whitespace. In some settings, Ctl-W erases backwards to first not-alphanumeric graphic symbol.

  • Ctl-X

    In certain word processing programs, Cuts highlighted text and copies to clipboard.

  • Ctl-Y

    Pastes back text previously erased (with Ctl-U or Ctl-W ).

  • Ctl-Z

    Pauses a foreground job.

    Substitute functioning in sure discussion processing applications.

    EOF (end-of-file) character in the MSDOS filesystem.

Whitespace

functions as a separator betwixt commands and/or variables. Whitespace consists of either spaces, tabs, blank lines, or any combination thereof. [9] In some contexts, such as variable assignment, whitespace is not permitted, and results in a syntax error.

Blank lines have no effect on the activeness of a script, and are therefore useful for visually separating functional sections.

$IFS, the special variable separating fields of input to certain commands. It defaults to whitespace.

To preserve whitespace within a string or in a variable, utilise quoting.

UNIX filters can target and operate on whitespace using the POSIX character class [:infinite:].

martinwithris.blogspot.com

Source: https://tldp.org/LDP/abs/html/special-chars.html

0 Response to "Capitulo 7 Reading and Writing Test Form a"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel