Sei sulla pagina 1di 11

======Declare the Shell in the Shell Script=====

#!/usr/bin/sh OR
#!/usr/bin/ksh OR
#!/usr/bin/csh OR
#!/usr/bin/bash OR

#!/bin/sh Declares a Bourne shell


#!/bin/ksh Declares a Korn shell
#!/bin/csh Declares a C shell
#!/bin/bash Declares a Bourne-Again shell

========Style in Shell Scripts=============


#!/usr/bin/ksh
#
# SCRIPT:
NAME_of_SCRIPT
# AUTHOR: AUTHORS_NAME
# DATE:
DATE_of_CREATION
# REV:
1.1.A (Valid are A, B, D, T and P)
#
(For Alpha, Beta, Dev, Test and Production)
#
# PLATFORM: (SPECIFY: AIX, HP-UX, Linux, Solaris
#
or Not platform dependent)
#
# PURPOSE:
Give a clear, and if necessary, long, description of the purpose of the shell
#
script. This will also help you stay focused on the task at hand.
#
# REV LIST:
#
DATE: DATE_of_REVISION
#
BY: AUTHOR_of_MODIFICATION
#
MODIFICATION: Describe what was modified, new features, etc-#
#
# set -n
# Uncomment to check your syntax, without execution.
#
# NOTE: Do not forget to put the comment back in or
#
#the shell script will not execute!
# set -x
# Uncomment to debug this shell script (Korn shell only)
############### DEFINE FUNCTIONS HERE ####################
##########################################################
##########################################################
################ BEGINNING OF MAIN #######################
##########################################################
# End of script

=======Unix Special Characters====


\(;#$?&*()[]`+
'' '' mostra cadeia de caracteres citada entre '', substituindo dia_da_semana=segunda-feira
o nome da variavel pelo seu conteudo
echo '' Hoje $dia_da_semana''
resultado : Hoje segunda-feira
' ' (aspas simples) mostra cadeia de caracteres citada
entre ', sem substituir o nome da variavel pelo seu
conteudo

Resultado : Hoje $dia_da_semana

` ` (crase) O resultado do comando usado em output

Ex : data=` date +%D`

\ transcreve un caracter especial


; separador de comando sequencial
? combina com qualquer caracter isolado

Ex : date ; ksh meu_shell ; date > /tmp/result &

* combina com qualquer cadeia de caracter


[a-z]* combina com algo que consista de caracteres
alfabeticos minusculos.
^string Procura a string somente no comeco da linha
String$ Procura a string somente no fim da linha
$@ - special parameter also specifies all command-line
arguments.
$* - Lista o conteudo de todos os parametros
$#

No. De parametros

$0

Parametro que contem o nome do programa

Ksh meuscript parm1 parm2


$0
$1
$2
# ! /bin/ksh
if (($# == 2)) then
echo ''numero do parametro correto''
fi

$1, $2, $3 Parametros fornecidos


${15} Dcimo quinto argumento
$*
- special parameter takes the entire list as one
argument with spaces between.
''$@''

========================== Command-Line Arguments======


()
(( ))
$(( ))
[]
[[ ]]
$( )
`command`

- Run the enclosed command in a sub-shell


- Evaluate and assign value to variable and do math in a shell
- Evaluate the enclosed expression
- Same as the test command
- Used for string comparison
- Command substitution
- Command substitution

============Shift Command=======
=================Operators==========================
++
+
!~
*/%
+<< >>

Auto-increment and auto-decrement, both prefix and postfix M=`expr 1 + 1`


Unary plus
Unary minus
Logical negation; binary inversion (ones complement)
Multiplication; division; modulus (remainder) M=`expr $M \* 3` M=`expr $X % 2`
Addition; subtraction
Bitwise left shift; bitwise right shift
Ex : 1>arq_ok 2>arq_erro

<= >=
<>

Less than or equal to; greater than or equal to


Less than; greater than M=`expr $X \< 2`
if test $M -eq 1 ; then echo TRUE ; fi
Equality; inequality (both evaluated left to right)
M=`expr $X == 2`
if test $M -eq 0 ; then echo FALSE ; fi
Bitwise AND

== !=
&

^
Bitwise exclusive OR
|
Bitwise OR
&&
Logical AND
||
Logical OR
=======Variaveis====
Global (existe enquanto a sessao estiver aberta)

Local (existe durante execucao do shell)

export nomevar=valor

nomevar=valor

Ex :
export TERM=vt100 (variavel de ambiente)
export DBDATE=Y4MD- (var. De ambiente)
export matricula=20044 (var global)

String
nome=Li
nome1=lliam
conc=$nome$nome1
echo $conc

cabec=''Relatorio do ano $ano''


dir_log=/tmp ; ls $dir_log
aluno=${nomes [$cont]}
parm1=$1
ls arq$var
dia=Segunda-feira ; echo ''Hoje dia $dia''

Inteiro
le cont=1 ou cont=1
let soma=$cont+2
let x'1 + 4' ou let x=1+4
let x=$x+1
utilisar let quando quizer manipular variavel

Array
${var [*]}
${#var[*]}
${#var[n]}

Mostra o conteudo do array inteiro


Mostra o numero de elementos (argumentos de um array)
Elementos posicionais de um array

set A nomes ana jose maria


echo ${nome[*]}
echo ${#nome[*]}

Seta array chanmado nomes com ana jose e maria


resp : ana jose maria
resp : 3
Se indexador passar o numero de elementos existentes,
sera retornado branco

Ambiente
$USER

Conteudo do comando whoami (quem o usuario da conta)

$PATH

Lista de diretorios a serem procurados pelo meus executaveis

$HOME

Mostra qual o diretorio home

$PS1

Mostra o que esta settado como prompt

$SHELL

Mostra a shell que esta sendo utilisada

$TERM

Mostra qual o tipo de terminal que esta sendo utilisado

$$

Numero do processo do comando corrente

Vetores & Ponteiros


VAR=(a b c d e)
echo ${VAR[1]}
resp : b
echo ${VAR[0]}

VAR=''VALOR''
POINTER=''VAR''
echo ${!POINTER}
resp : VALOR

resp : a

======== Control Structures ======


If Statement
if (( expressao aritimetica))
then
commands
fi

====comparacao numerica====
A=5 ; b=7
if (($a== $b)) then
echo '' valores iguais''
else
echo ''valores differentes''
fi

if [testes condicionais]
then
commands
fi

===comparacao testes condicionais====


if [[ -z $parametros]] then
echo '' ERRO nao foi passado parametros !!!''
exit
fi

=========if..then=============
if [ test_command ]
then
commands
else
commands
fi

====comparacao de strings
a=inteiro ; b=metade
if [[$a = $b]] then
echo ''variaveis iguais''
else
echo '' variaveis diferentes''
fi
===testa se variavel tem conteudo====

=======if..then..elif===============
if [ test_command ]
then
commands
elif [ test_command ]
then
commands
elif [ test_command ]
then
commands
.
.
else (Optional)
commands
fi

-n str : retorna verdadeiro se variavel nao for nula


-z str : retorna verdadeiro se variavel for nula
if [[-z $matricula ]] then
echo '' variavel matricula Nao inicialisada''
fi
matricula=3254
if [[ -n $matricula ]] then
echo ''variavel matricula inicializada''
fi

Check the Return Code test


$?
Condicao shell

verdadeira se...

- d file

Se diretorio

-f file

See file

-r arquivo

Exisir arq. legivel

-w arquivo

Existir arq. gravavel

-x arquivo

Existir arq. executavel

-a arquivo

Se arquivo existe

-s arquivo

Se arquivo existe e nao


vazio

-O arquivo

Se o usernae que esta


logado o owner

test -d /usr/local/bin
if [ $? -eq 0 ] # Check the return code
then
echo /usr/local/bin does exist
else
echo /usr/local/bin does NOT exist
fi
or
if test -d /usr/local/bin
then
echo /usr/local/bin does exist
else
echo /usr/local/bin does NOT exist
fi

-G arquivo

Se o gid do username que


esta logado o mesmo
arquivo

test -r nomearq
echo $ ?
var=5
echo $ ?

or
If [ -d /usr/local/bin ]
then
echo /usr/local/bin does exist
else
echo /usr/local/bin does NOT exist
fi

(=0) sucesso

echo $var4
echo $ ?
(=1) sem sucesso

For statement
for loop_variable in argument_list
do
commands
done

While statement
while test_command_is_true
do
commands
done

Until statement
until test_command_is_true
do
commands
done

Case
case $variable in
match_1)
commands_to_execute_for_1
;;
match_2)
commands_to_execute_for_2
;;
match_3)
commands_to_execute_for_3
;;
.
.
.
*)
(Optional - any other value)
commands_to_execute_for_no_match
;;
esac

Using break, continue, exit, and return

========A Function Form=======


function function_name
{
commands to execute
}
or
function_name ()
{
commands to execute
}

==== Shell Script Commands =======

passwd - Change user password


pwd

- Print current directory

cd

- Change directory

ls

- List of files in a directory

wildcards
- *matches any number of characters, ? matches a
single character
file

- Print the type of file

cat

- Display the contents of a file

pr

- Display the contents of a file

pg or page

- Display the contents of a file one page at a time

more

- Display the contents of a file one page at a time

clear

- Clear the screen

cp or copy

- Copy a file

chown

- Change the owner of a file

chmod
- Change file modes, permissions
777 tudo #e permitido para todos
700 s#o o utilizador tem todas as permiss~oes
000 nada para ningu#em...
755 s#o o utilizador pode adicionar/remover
644 s#o o utilizador pode escrever
600 s#o o utilizador pode ler e escrever
666 todos podem ler e escrever
rm

- Remove a file from the system

mv

- Rename a file

mkdir

- Create a directory

rmdir

- Remove a directory

grep

- Pattern matching

egrep

- grep command for extended regular expressions

find

- Used to locate files and directories

date

- Display the system date and time

echo

- Write strings to standard output

sleep
seconds

- Execution halts for the specified number of

wc
a file

- Count the number of words, lines, and characters in

head

- View the top of a file

tail

- View the end of a file

diff

- Compare two files

sdiff
- Compare two files side by side (requires 132character display)
spell

- Spell checker

lp, lpr, enq, qprt - Print a file


lpstat

- Status of system print queues

enable

- Enable, or start, a print queue

cal

- Display a calendar

chmod u+rwx,g+rx,o+r my_script.ksh

who

- Display information about users on the system

- Extended who command

last

- history about users

whoami - Display $LOGNAME or $USER environment parameter


who am I
- Display login name, terminal, login date/time, and
where logged in
f, finger - Information about logged-in users including the users .plan
and .project
talk

- Two users have a split screen conversation

write

- Display a message on a users screen

wall

- Display a message on all logged-in users screens

rwall

- Display a message to all users on a remote host

rsh or remsh

- Execute a command, or log in, on a remote host

df

- Filesystems statistics

ps

- Information on currently running processes

netstat

- Show network status

vmstat

- Show virtual memory status

iostat

- Show input/output status

uname
- Name of the current operating system, as well as
machine information
sar

- System activity report

basename

- Base filename of a string parameter

man

- Display the on-line reference manual

su

- Switch to another user, also known as super-user

cut

- Write out selected characters

awk

- Programming language to parse characters

sed

- Programming language for character substitution

vi

- Start the vi editor

emacs

- Start the emacs editor

>>

- Append to the end of a file

<<
mail -s 'Backup status' vivek@nixcraft.co.in<<EOF
The backup job finished.
End date: $(date)
Hostname : $(hostname)
Status : $status
END_OF_EMAIL
EOF
>

- Redirect, create, or overwrite a file

$ mysql bancodedados < base.sql


$ bash < comandos.txt

Chamaremos este arquivo de comandos.txt,


com o contedo:
cd /root
ls
cd /usr/
ls
cd /etc
cat /etc/passwd

cd /usr/local/bin
pwd
======silent running=====
$ ls arquivonaoexistente > /dev/null 2> /dev/null
|
|--stderr
|--stdout
or
$ ls arquivonaoexistent > /dev/null 2>&1

$ sort < arquivo > arquivo_ordenado


$ cat arquivo.txt | sort
$ cat arquivo.txt | sort > arquivo_ordenado.txt
$ sed -e ''s/shell/Shell/g'' capit1

$ sed -e '' s/shell/Shell/g'' <capit1> novocapit1


$ sed -e ''s/shell/Shell/g'' capit1 1> novocapit1 2> erro
|

Vamos por partes: primeiro redirecionei a


sada padro para /dev/null (> /dev/null) e
logo em seguida redirecionei a sada de erros
para o mesmo lugar que a sada padro
(2>&1). O caracter especial & atuou como
uma referncia para a sada padro. Se no
houvesse o &, a sada de erros seria
direcionada para um arquivo comum chamado
1. Por fim, este comando tambm faz com
que os dois tipos de sada sejam enviados para
/dev/null e, por consequncia, anulados.
# cada linha do arquivo passa para sort ordena
mostra na tela e envia para um arquivo
# saida de cat vai para sort que ordena e joga
na tela
# saida de cat vai para sort que ordena e joga
na tela e cria arquivo
# o comando sed abrira o arquivo capit1 como
stdin e passarao arquivo para stdout (terminal)
enquanto muda todas as ocorrencias de ''shell
para ''Shell''
# ainda estaria direcionando para terminal

- Pipe, used to string commands together

||
- Logical ORcommand1 || command2execute
command2 if command1 fails
&

- Execute in background

&&
- Logical ANDcommand1 && command2
execute command2 if command1 succeeds
Kill
ps
ps -f
ps -ef
ps -A
ps -Kf
ps auxw

The users currently running processes


Full listing of the users currently running processes
Full listing of all processes, except kernel processes
All processes including kernel processes
Full listing of kernel processes
Wide listing sorted by percentage of CPU usage, %CPU

$Cut
$ cat /etc/passwd | cut -d : -f1 | sort | uniq

# pega 1era palavra de cada linha da saida de


passwd

UPCASEVAR=$(echo $VARIABLE | tr [a-z] [A-Z])


DOWNCASEVAR=$(echo $VARIABLE | tr [A-Z] [a-z])

# Used for lower to uppercase


# Used for upper to lowercase

typeset -u VARIABLE
VARIABLE=True
echo $VARIABLE
TRUE

(-l converte para maiusculo)

typeset -l VARIABLE
VARIABLE=True
echo $VARIABLE
true

(-l converte para minusculo)

===============Commands for Real-Time User Communication====

wall
rwall
write
talk

Writes a message on the screen of all logged-in users on the


local host.
Writes a message on the screen of all logged-in users on a
remote host.
Writes a message to an individual user. The user must currently
be logged-in.
Starts an interactive program that allows two users to have a
conversation. The screen is split in two, and both users can see
what each person is typing.

========Built-In Shell Functions======


abs
Absolute value
log
Natural logarithm
acos
Arc cosine
sin
Sine
asin
Arc sine
sinh
Hyperbolic sine
cos
Cosine
sqrt
Square root
cosh
Hyperbolic cosine
tan
Tangent
exp
Exponential function
tanh
Hyperbolic tangent
int
Integer part of floating-point number
==============Running Commands on a Remote Host===================
ssh user@hostname command_to_execute

===========Cron Tables==========
By default, any user can create a cron table with the crontab -e command
but the Systems Administrator can control which users are allowed to create and edit cron tables with the cron.allow and
cron.deny files. When a user creates his or her own cron table the commands, programs, or scripts will execute in that
users environment. It is the same thing as running the users $HOME/.profile before executing the command.
1 0 1 1 * /usr/bin/banner Happy New Year > /dev/console
| | | | |
| | | | |---weeday (0-6 for sunday to saturday)
| | | |-----month (1 through 12)
| | |-------Day of the month (1 through 31)
| |---------Hour (0 through 23)
|-----------Minute (0 through 29)
5,20,35,50 * * * *

/usr/local/bin/systemcheck.ksh

============at Command===========
executes commands at a specific time

2>&1 >/dev/null

====================

============getopts to Parse Command-Line Arguments ===========

Potrebbero piacerti anche