Este documento es una traducción de Introduction to Bash Shell Scripting de Donald A Kassebaum, siéntase libre de adicionar más ejemplos o complementar con lo que considere de utilidad.

Introducción a la creación de guiones de Bash

Referencias

Comienzo

Obtención de Ayuda

man

Get off information about commands

man -k

Get off information via keyword

info

Read info documents

help

Show help on shell built-in commands

command --help

Help on command .i.e. cp --help Will give help on cp

bash -c "help"

Short help on bash

bash -c "help set"

Short help on bash options

Caracteres especiales

Space

Argument separator

\

Quote a single character A \ followed by a carriage return extend the current line

'

Quote rext with spaces in it i.e. 'Hello world'

$'

Quote allows string expansion, backslash-escaped characters

"

Quote rext, expands variables and command substitution

`

Command substitution i.e. echo "The date is `date`"

$

Denote a shell variable

#

Comments the rest of the line

;

Commands separator

(commands)

Run multiple commands in a subshell

Control-C

Interrupt a command

Control-D

Sends End of File from terminal

Control-U

Erases the entire command line

Control-\

Is a stronger terminate than Control-c

Control-Z

Suspend process

Redirección, tuberías y filtros

-

Standard In for some commands

0

Standard In

1

Standard Out

2

Standard Error

>2 &1

Redirect standard error to standard out

&>

Redirect standard error & standard out

<

Redirect input

>

Redirect output

>>

Concatenate output to file

<<

Here Is File for scripts

|

Pipe

tee

Command write to file and standard out

tee

-a FILE #Allow appending to FILE

xargs

Build command from standardin

Comodines

*

Wildcard for any character(s)

?

Wildcard for single character

[set]

Wildcard for character in set

[^set]

Wildcard for not the character in the set

[!set]

Wildcard for not the character in the set

{ab,dc}

Wildcard for alternate between commas

All

wildcard work with existing files

Only

{} alternate work to create files

Control de procesos

(command1; command)

Run command1, then command2 in subshell

command1&&command

Run command1, then command2 if command1 successes

command1||command

Run command1, then command2 if command1 fails

Expresiones Regulares

Definición
caracteres de patrones de texto y metacaracteres

A continuación algunos metacaracteres.

\

Escape character

Metacaracteres con un solo caracter

.

Matches any one character

[...]

Matches any one character in a set

[^...]

Matches any one character not in the set

Cuantificadores

*

Matches the previous character zero or more times

\{n\}

Matches the previous character n times

\{n,m\}

Matches the previous character at least n & at most m

\{n,\}

Matches the previous character n or more times

Anclas

^

Matching at the start the line

$

Matching at the end of line

Agrupamiento \( \)

Comandos que usan expresiones regulares

awk
Pattern scanning and text processing language
ed
Line-oriented text editor
egrep
extended grep
emacs
Emacs full screen text editor
ex
Line-oriented text editor
expr
Command evaluates an expression
fgrep
Grep from patterns in a file
gawk
GNU pattern scanning and processing language
grep

Searches file for pattern (also see fgrep & egrep)

grep [OPTIONS] PATTERN [INPUT-FILE...] -E same as egrep

-c

Count

-e

pattern (for multiple pattern on line)

-f

same as fgrep

-i

Ignore case

-l

Only list files containing pattern

-q

Quit (No output, only Return Code)

-v

Invert sense mode

perl
Perl scripting
python
Python scripting
sed
Applies a set of user-specified editing command to a file

sed [OPTIONS] 'sed_command' [INPUT_FILE...] -n Suppress automatic printing

-e

expression - sed_command

substitute

other_text for some_text sed 's/some_text/other_text/g' FILE > NEWFILE

multiple

changes sed -e 's@abc@def@g' -e 's@xyz@mno@g' FILE

print

out line with faq in them sed -n '/faq/p' FILE

change

Page ### to (Page ###) at end of line sed 's/Page [0-9]+$/(&)/' file # & replace the match

delete

blank lines sed '/^[ \t]*$/d

tcl
Tool command language
vi
Full screen text editor

Variables de Shell

Variables de shell embebidas

CDPATH

Path of shortcuts for cd (like PATH)

COLUMNS

Numbers of columns on the display

EDITOR

Path for editor

HISTSIZE

Number of commands in command history (default 500)

IFS

Input Field Separator

LINES

Numbers of lines on the display

OFS

Output Field Separator

SECONDS

Seconds that this shell is running

SHELLOPT

Colon separate list of shell options

Variables de Ambiente

export var

Will make a variable an environment variable

HOME

User's home directory

LOGNAME

User's name

MAIL

Name of user's mailbox

PATH

List of directories to be search by the shell to find programs whose names are type as commands

PS1

String that is used by the shell prompt

PWD

Name of current directory

SHELL

Name of current shell

TERM

The kind of terminal being used

Environment variable are global to shell and subshells

Variables de usuario

Pueden ser en mayúsculas o minúsculas

var=value

Definir una variable

var=""

Definir la variable von valor nulo

local var

Definir la variable en alcance local

Variables posicionales

Variables especiales

Algunos comandos útiles en los scripts

Coloreado de scripts

Funciones de shell y scripts

Funciones

Scripts

Opciones de depuración para los scripts

Operaciones con variables

Uso de variables

Paso de una variable a un programa o un script

Arreglos

Establecer valores para las variables al ejecutar un comando

Operaciones aritméticas

Operadores aritméticos

Operaciones de prueba

Operaciones en cadenas

Operaciones con patrones

El versátil 'expr'

Control de flujo

if - Información general

if/then/else or if/then/elif..

            if condition
              then statements...
              [else statements...]
            fi

            if condition
              then statements...
              [elif condition
                then statements...]
                [else] statements...]
            fi

Valor de retorno de una función

for

            for name [ in list ] do
              statements
            done

            for  variable = start to end do
              statements
            done

while/until

            while condition do
              statements
            done

            until condition do
              statements
            done

break/continue

case

      case expression in
        pattern1[|pattern11] } statements ;;
        pattern2[|pattern21] } statements ;;
        ...
      esac

Interfaces de usuario

select

Opciones por la línea de comandos

Operaciones de E/S en scripts

Manejo de procesos

Señales

Trampas

Ejemplos de scripts o funciones útiles

# Function top5 Example how to set defaults # Usage top5 {n} #list n processes 
function top5 { 
  ps -ef | head -${1:-5} 
}

# Function hereis Example of HERE IS FILE and handling arguments 
# Usage hereis word1 word2 ... 
function hereis {
  for name in "$@" 
     do 
     cat <<MSG This is an example of an HERE IS FILE. One argument is ${name}. The date is `date`. 
MSG 
   done 
}

# Function pick Return selected items by user 
# Usage: .e.g var=`pick *` 
function pick { 
   for name in $@ ; do       #for each item in argument list 
       echo -n "$name (y/n/q)?" >/dev/tty #ask user to select 
       read ans #read answer from standard in 
       case $ans in #Check choices 
          y*) echo $name;; #selected 
          q*) break;; #skip rest of arguments 
          *) continue;; #skip item 
        esac 
     done 
}

# Function acal Display a nicer calendar 
# but will accept Alphabetic month 
function acal { 
    m="" 
    case $# in 
    0) cal; return;;        #no arguments 
    1) m=$1; y=`date +%Y`;; #1 argument 
    2) m=$1; y=$2;;         #2 arguments      
    esac

    case $m in 
    Jan*|jan* ) m=1;; 
    Feb*|feb* ) m=2;; 
    Mar*|mar* ) m=3;; 
    Apr*|apr* ) m=4;; 
    May|may } m=5;; 
    Jun*|jun* ) m=6;; 
    Jul*|jul* ) m=7;; 
    Aug*|aug* ) m=8;; 
    Sep*|sep* } m=9;; 
    Oct*|oct* ) m=10;; 
    Nov*|nov* ) m=11;; 
    Dec*|dec* ) m=12;; 
    [1-9]|1[0-2] ) ;; #numeric month 
    *)       ) y=$m; m="";; 
    esac 
    cal $m $y 
}

## Function selectex - Example select 
# 
function selectex () { 
   choices="/bin /usr /home" 
   select selection in $choices; do 
    if [ $selection ]; then 
      ls $selection 
      break 
    else 
      echo 'Invalid selection' 
    fi 
   done 
}

# Function fwhich Which command in $PATH is executed 
# 
function fwhich { 
   if [[ $# -eq 0 ]] ; 
     then cat << EndOfHelp 1>&2; return 2 
             Usage fwhich command #Example of parsing the $PATH 
                 Return 0 - found 
                 Return 1 - not found 
                 Return 2 - No arguments 
EndOfHelp 
    fi 
    for path in `echo $PATH | sed 's/^:/.:/ 
                                   s/::/.:/g 
                                   s/:$/:./ 
                                   s/:/ /g'`
    do 
      if [[ -x $path/$1 ]] ; # does executable file exists here? 
         then echo $path/$1 # found it 
         return 0 
      fi 
    done 
    return 1 # not found 
}

# Name: overwrite Copy standard input to output after EOF 
function overwrite { 
   if [[ $# -lt 2 ]] ; 
      then echo "Usage: overwrite file command [args]" 1>&2; return 2 
   fi

 file=$1; shift 
 new=/tmp/overwrite1$$; pld=/tmp/overwrite2$$ 
 trap 'rm -f $new $old; return 1' 1 2 15 # clean up files 
 "$@" > $new 
 if [[ $? -eq 0 ]] ; # collect output 
   then # command completed successfully 
     cp $file $old # save original file 
     trap '' 1 2 15 # we are committed; ignore signals 
     cp $new $file # copy new file into file 
     rm -f $new $old # remove temp files 
    else 
     echo "overwrite: $1 failed, $file unchanged" 1>$2 
     return 1 
    fi 
}

# Name: zgrep 
# Purpose: caseless grep of gzip files 
# Usage: zgrep text files.gz 
# 
function zgrep { 
    if [ $# -eq 0 ] ; then 
        echo "Usage: zgrep grep_text files.gz" 
        return 2 
     fi 
      text=$1 
      shift 
      while [ $# -gt 0 ]
        do 
           echo $1 gzip -cd $1 | grep -i $text 
           shift
        done
}

# Name: hgrep 
# Purpose: highlighting grep 
# Usage: hgrep pattern files 
# 
function hgrep { 
   if [ $# -lt 2 ] ; then 
      echo "Usage: hgrep pattern files" 
      return 2 
   fi 
     pattern=$1;shift 
     sep=$'\001' #note use of $' ' to create control characters 
     bold=$'\e[1m'; off=$'\e[0m' 
     underline=$'\e[4m'; reverse=$'\e[7m' #other choices of highlighting 
     sed -n "s${sep}${pattern}${sep}${reverse}&${off}${sep}gp" $* 
} 


CategoriaAyudaInterfazDeComandos

ProgramarEnBash (last edited 2009-07-15 15:25:41 by localhost)