Nohup sqlplus con parametri

attrib chmod
backup tar
dir ls
cls clear
copy cp
del rm
deltree rm -R
edit vi
format fdformat
move / rename mv
type less
cd cd
more < file more file
md mkdir
win startx
cd pwd Posizione nelle directory
dir ls -l Directory con files e dimensioni
dir ls -lt in ordine di data
cd.. cd ..
ren mv muovi/rinomina
chkdsk df -k Spazio occupato
exec login >> nuova connessione

Note: UNIX commands and filenames are case sensitive!
man command display manual page for command man ls; man -k edit
ls [dirname] lists files in dirname ls; ls -ltr; ls *.t*
pwd print working directory (Where am I in the filesystem?) pwd
cd directory change current directory cd /u/cs370/george; cd ..
locate string find all occurances of string in the filesystem; generally only on Linux systems locate edit
grep string filename find all occurances of string in the file filename grep root /etc/passwd
pipe "|" redirect output from one command into input for another command locate edit | grep png
cat [file1...filen] concatenate files to output (print files) cat out1 out2 > out3
cp file1...filen dir copy n files to dir cp *.c ../old
cd directory change current directory cd /u/cs370/george
mkdir name create a directory mkdir bin
rmdir name remove a directory rmdir tmp
more file page through file one screen at a time more junk.c
lpr -Pprinter file spool file to printer lpr -Pnext1 output
pwd display name of the present working directory
vi file edit file, see vi Quick Reference vi prog.c
xemacs file edit file using the xemacs editor xemacs prog.c
mv file1 file2 move file1 to file2 mv old new
df disk free: show space left on disk df
du disk usage: show space used in a directory (note: ~ means "my home directory") df ~
rm file1 [file2...filen] remove the specified files rm a.out
exit or Ctrl-D logout exit; Ctrl-D

vi (Visual Editor)
h Cursor left i Insert text before cursor, end with ESC
l Cursor right I Insert at beginning of current line
j Cursor down a Append text after cursor, end with ESC
k Cursor up A Append at end of line, end with ESC
+ Move to beginning of next line o Open new line below cursor
- Move to beginning of previous line O Open new line above cursor
0 Move to beginning of current line r Replace a character
% Move to matching [,],(,),{,} R Replace characters; end with ESC
$ Move to end of current line s Substitute string for a char, end with ESC
w Word forward 4s Substitute string for 4 chars, end with ESC
b Word backward x Delete a character
Ctrl-F Foreward one screen dd Delete a line
Ctrl-B Backward one screen D Delete to end of line
G Go to last line of file d Delete to beginning of line
xG Go to line x dw Delete one word
) Move to next sentence dtch Delete to ch
( Move to previous sentence p Insert last yank or delete after cursor
} Move to next paragraph P Insert last yank or delete before cursor
{ Move to previous paragraph yy Yank line into buffer
/str Search forward for str "chyy Yank into named buffer ch
?str Search backward for str digits Repeat next command that many times
n Repeat last/ or ? search . Repeat last command which changed text
fch Find next ch foreward u Undo last change
Fch Find next ch backward J Join next line with this one
ZZ Save file and exit :w Save file and continue
:wq Save file and exit :q! Exit without saving changes

On-line Help
man display reference manual pages man cmd_name
Basic Options:
-k locates commands by keyword lookup man -k keyword
-s specifies a chapter or section to look in man -schap# cmd_name
-u basic usage description man -u
whereis locate the executable, source, and man page files whereis command
Basic Option: whereis -h
-h basic usage description
Communicating With Other Users
chfn change finger entry (disabled on eden and rci. See note 1 at bottom.) chfn
finger lists information about users finger NetID/username
Basic Option: finger -h
-h basic usage description
from see who your mail is from from
Basic Option: from -h
-h basic usage description
ftp file transfer protocol ftp computer.domain
Transfers files from one networked computer where you have an account to another where you have an account.
mail not supported mail
mesg permit or deny messages from write and talk mesg y or mesg n
pine mail program recommended by RUCS pine
Basic Option: pine -h
-h basic usage description
talk "talk" to another currently logged in user talk NetID/username
telnet login on another computer on the network telnet computer
w list who is on the system and what they are doing w
who list who is on the system who
whodo list who is on the system and what they are doing whodo
write send an interactive message to another user write NetID/username
Dealing with the File System
cat concatenate and display arguments to standard output cat file
cd change directory cd path
Note: given a full or relative path, set the working directory as specified; without arguments set the working directory to the login directory
Basic Option: cd -h
-h basic usage description
chmod set the protections on a file chmod code file
In the numeric mode the three numbers represent the protections for the user, group and others. Each number is a sum of 1 (for execute access), 2 (for write/delete access) and 4 (for read access). "chmod 750 file.name" sets full access for the user, read and execute for the group and no access for others chmod ### file
In the symbolic mode the options first indicate whose access is to be changed u (user, you), g (group), o (other), or a (all); then indicate the type of action + (add), - (delete), or = (set); and then specify the access to be set r (read), w (write/delete), or x (execute). &qiot;chmod o-rwx file.name" denies others from having any access to file.name and has no affect on user/group access chmod ugoa+-=rwx file
Basic Option: chmod -R code file
-R descend into subdirectories
cp copy files cp fromfile tofile
Basic Option: cp --help
--help basic usage description
diff compares two files and reports the differences diff file1 file2
Basic Option: diff --help
--help basic usage description
du display disk usage du
NOTE: On rci 'du' and 'du -k' both yield results in 1 kilobyte blocks, while on eden 'du' yields results in ½ kilobyte blocks and 'du -k' yields results in 1 kilobyte blocks.
Basic Options: du -k
-k show usage in 1 kilobyte blocks du ---help
--help basic usage description
file determine the type of a file file filename
Basic Option: file -h
-h basic usage description
ftp file transfer protocol ftp computer.domain
Transfers files from one networked computer where you have an account to another where you have an account.
grep search for a character string in a file grep string file
Basic Options: grep -v string file
-v show lines that do not contain the string grep -h
-h basic usage description
gzip compress a file to take up less space gzip filename
Basic Option: gzip -h
-h basic usage description
gunzip re-expand compressed files gunzip filename
Basic Option: gunzip -h
-h basic usage description
head Show the first 10 lines of a file head filename
Basic Options: head -20 filename
-# show first # lines of the specified file head --help
--help basic usage description
ispell check the spelling of the contents of a file ispell file
Basic Option: ispell -h
-h basic usage description
less browse or page through a text file. less file
Usage: press the space bar to go forward a page, type b to go back a page and type q to quit.
Basic Option: less -h
-h basic usage description
lpq check the status of a print queue lpq
Basic Option: lpq -Pprinter_name
-Pprinter specifies the printer to be checked
lpr send a job to a print queue lpr options file(s)
Basic Options:
-Pprinter specifies the printer
-Nnote print note on burster page
-m send mail upon completion
lprm remove a print job from a print queue lprm print_job_#
ls list the contents of a directory ls options files(s)
Basic Options:
-a all files
-d list directories not their contents
-F mark directories with /, executable files with *, symbolic links with @, and sockets with =
-l long listing showing protections, number of links, owner, size, and time of last modification
-s size in kilobytes
--help basic usage description
mkdir create a new subdirectory in the current directory mkdir subdir
create a new subdirectory, in the indicated target directory mkdir subdir targetdir
Basic Option: mkdir --help
--help basic usage description
more browse or page through a text file. more file
Usage: press the space bar to go forward a page, type b to go back a page and type q to quit.
Basic Option: more -h
-h basic usage description
mv move or rename files mv fromfile tofile
Basic Option: mv --help
--help basic usage description
pr prepare text for printing with headers and page breaks pr file
Basic Options: pr -h "header text" file
-h "header text" set the page header pr --help
--help basic usage description
printers Display the available printers printers
pwd display the current directory's full pathname pwd
quota check to see if over allowed usage, no response if not quota
Basic Option:
-v verbose, show status even if not over quota quota -v
With this option eden will display more information than rci.
rm remove (delete) files rm file
Basic Options:
-i interactive, ask before removal rm -i file
-r recursive, descend into subdirectories removing files and then containing directories. rm -r directory
--help basic usage description rm --help
Note: Once a file is deleted, you can't undelete it. Use the -i option to have UNIX ask if you are sure about removing the file.
rmdir remove empty directories rmdir dirname
Basic Option: rmdir --help
--help basic usage description
sort sort input sort filename
Basic Option: sort -n filename
-n sort numerically.
tail show last 10 lines of a file tail filename
Basic Options: tail -20 filename
-# show last # lines of the specified file tail --help
--help basic usage description
touch update the time stamp on existing files, create new empty files touch file
Basic Option: touch --help
--help basic usage description
umask display or set the accesses to be denied on newly created files umask ###
Each # indicates which accesses (if any) are to be denied to a class of user. The first affects the user (you), the second affects the group, and the third affects all others. If a # is 0 then no access is denied that class of user, 1 denies execute access, 2 denies write access, 4 denies read access, 3 is the sum of 1 and 2 (no execute or write access), 5 is the sum of 4 and 1 (no execute or read access), etc. umask 077 would allow full access by the user and deny all others any access. Usually this command is placed in the file .login to be executed every time you log in.
If used alone, display current value, leading zeros not shown umask
wc display the number of lines, words and characters in a file wc filename
Basic Option: wc --help
--help basic usage description
Work Environment
alias create a new name for a command or series of commands alias newname oldname
chsh change login shell (disabled on eden and rci. See note 1 at bottom.) chsh
clear clear the terminal screen clear
echo display indicated text or variable contents echo text
echo $varname
exit log off the system exit
id display your system ID numbers id
if given a NetID/username, display their ID numbers id username
logout log off the system logout
passwd change the login password (disabled on eden and rci. See note 1 at bottom) passwd
printenv show your current environment variable settings printenv
if given an environment variable name display that setting printenv varname
script make a copy of everything displayed on the screen script filename
Useful for capturing error messages and program execution
Usage: to end scripting, type a d
Options: script -a filename
-a append to file rather than overwrite script -h
-h basic usage description
setenv set environment variables setenv varname value
unalias unset an alias that was previously set unalias aliasname
unsetenv unset environment variables unsetenv varname
reset reset the terminal screen reset
whoami display the current NetID/username whoami
Basic Option: whoami -h
-h basic usage description
Controlling your jobs
bg run the indicated job in the background bg %job#
fg move a job from the background to the foreground fg %job#
jobs list current jobs and their status jobs
Basic Option: jobs -h
-h basic usage description
kill terminate a process kill %job#
kill process#
nohup run a command immune to hang-ups nohup command
Notes: Standard input, output, and error must be redirected or will be lost. Over use or frivolous use of this can be considered abuse of the system.
ps list current processes ps
News Programs
nn news reading program nn
if given a newsgroup name, read only that newsgroup nn newsgroupname
nnpost news posting utility nnpost
Emacs Text Editor
emacs the emacs editor emacs filename
teach-emacs the emacs on-line tutorial teach-emacs
adb general purpose program debugger adb objectcode
cc C compiler: (see note 2 at bottom) cc file.c
Basic Option: cc -flags
-flags basic usage description
CC C++ compiler: (see note 2 at bottom) CC file.c
Basic Option: CC -flags
-flags basic usage description
dbx program debugger dbx executable
f77 FORTRAN 77 compiler: (see note 2 at bottom) f77 file.f
Basic Option: f77 -flags
-flags basic usage description
f90 FORTRAN 90 compiler: (see note 2 at bottom) f90 file.f90
Basic Option: f90 -flags
-flags basic usage description
gcc Gnu C compiler: (see note 2 at bottom) gcc file.c
g++ Gnu C++ compiler: (see note 2 at bottom) g++ file.c
lint attempts to detect features of C programs that are likely to be errors, non-portable, or wasteful lint file.c
Basic Option: lint -flags
-flags basic usage description
make facilitates compilation of several program modules make
Basic Option: make -h
-h basic usage description
pc Pascal compiler: (see note 2 at bottom) pc file.p
Basic Option: pc -flags
-flags basic usage description
Web Browsers
lynx text only web browser, usable in telnet sessions lynx
Basic Option: lynx -h
-h basic usage description
netscape graphic web browser, usable on X terminals netscape &
Basic Option: netscape -h
-h basic usage description

cal display the calendar of the current month cal
if given a complete year number (03 = 3, not 2003), display that year cal yr#
if given a month and year number (01 = January), display that specific month cal mo# yr#
date show the current system date and time date
dict electronic dictionary, thesaurus, familiar quotations, and CIA world factbook dict
Options: dict -d
-d dictionary, default action dict -t
-t thesaurus dict -q
-q familiar quotations dict -w
-w CIA world factbook
units converts units in one scale to another units
Basic Option: units -h
-h basic usage description
Note 1:
On eden and rci the standard UNIX user commands chfn, chsh, and passwd have been disabled and replaced by web tools, please go to http://www.rci.rutgers.edu/tools.php or http://www.eden.rutgers.edu/tools.php to perform these functions.
Note 2:
In order to use the math libraries of linkable subroutines, the last item on the compile command must be " -lm", as in "cc -o demo demo.c -lm"
Metacharacters are a group of characters that have special meanings to the UNIX operating system. Metacharacters can make many tasks easier by allowing you to redirect information from one command to another or to a file, string multiple commands together on one line, or have other effects on the commands they are issued in. The following table lists some of the metacharacters for the Rutgers default shell (the T shell).
UNIX interprets a space as a separator not as a character.
* A wild card character that matches any group of characters of any length, allowing a user to specify a large group of items with a short string. For example, to specify all the files that start with 'abc', you use abc*.
? A wild card character that matches any single character. Thus ls ??? lists files in the current directory whose names are only three characters long, while ls ???.* lists those files with a three letter main name and any extension.
[..] A set of characters that can be matched. Thus ls [a-c]*.??? lists all files that begin with a, b, or c and have a three letter extension and lpr [ad]* prints all files that begin with a or d.
$ Indicates that the following text is the name of a shell (environment) variable whose value is to be used.
| Separates commands to form a pipe (see redirection in "Intermediate Use Of The UNIX Operating System").
< Redirect the standard input (see redirection in "Intermediate Use Of The UNIX Operating System").
> Redirect the standard output (see redirection in "Intermediate Use Of The UNIX Operating System") to replace current contents.
>> Redirect the standard output (see redirection in "Intermediate Use Of The UNIX Operating System") to append to current contents.
>& Redirect the standard output and standard error (see redirection in "Intermediate Use Of The UNIX Operating System") to replace current contents.
>>& Redirect the standard output an standard error (see redirection in "Intermediate Use Of The UNIX Operating System") to append to current contents.
% Introduces a job name (see multitasking in "Intermediate Use Of The UNIX Operating System").
& Place a process into the background (see multitasking in "Intermediate Use Of The UNIX Operating System").
() Encloses a sequence of commands or pipes to be executed as a single command.
! Precedes a history substitution (see "man history")
; Separates sequences of commands (or pipes) that are on one line.
&& Separates two sequences of commands or pipes the second of which is executed only if the first succeeds.
|| Separates two sequences of commands or pipes the second of which is executed only if the first fails.
\ Used to "quote" the following metacharacter so it is treated as a plain character, as in \*.

In the default Rutgers UNIX shell (the T shell) with the default editor set to emacs, commands may be edited and previous commands retrieved using control characters:
a move the cursor to the beginning of the line
b move the cursor to the left
c abort the current command
d if not at end of the command line, delete the character at the cursor
if at end of command line, list possible command (or file) name completions
e move the cursor to the end of the line
f move the cursor to the right
h delete the character to the left of the cursor
k erase from the cursor to the end of the line
l clear the screen and display current line
n bring up next command line
p bring up previous command line
q continue displaying to the screen (see s)
r redisplay the current line
s stop displaying to the screen (see q)
t exchange the character to the left of the cursor with the character at the cursor
u erase the current line
w will erase from the cursor to the beginning of the line
y yank back the last item erased by k, u, or w
b move the cursor to the left one "word"
f move the cursor to the right one "word"
c move the cursor to the right one "word", capitalizing while moving
l move the cursor to the right one "word", making lower case while moving
u move the cursor to the right one "word", making upper case while moving


questo programma di editor si chiama "vi"
di seguito sono elencati i comandi principali:

"q" per uscire
"esc" determina la fine inserimento
"i" inserimento riga
"o" inserisce nella riga sottostante
"r" sostituisce un carattere
"x" cancella un carattere
"yy" oppure "Y" per selezionare una riga
"O" aggiunge una riga sopra
"dd" cancellazione di un riga e il cursore si posiziona nella riga sopra
"p" duplica una riga sotto
"P" duplica una riga sopra
"D" cancella la riga e il cursore si posiziona all'inizio della riga stessa
"3dd" cancella + righe. Col comando "p" le reinserisce in un punto del file.
"3x" simile a "3dd"
"3yy" seleziona + righe che si possono reinserire in qualsiasi punto del file
"." ripete esattamente l'ultima operazione eseguita.
"CTRL F" va avanti di una pagina
"CTRL B" va indietro di una pagina
"w" serve per spostarsi di parola in parola in avanti
"b" serve per spostarsi di parola in parola indietro
"R" sostituisce tutti i carattere dalla posizione del cursore in poi
"dw" cancella dalla posizione del cursore fino alla fine della parola
"cw" all'inizio della parola cambia tutta la parola
"i + invio" serve per spezzare la riga
"J" concatena la riga dove il cursore si trova con la riga successiva
":w" salva il file
":q" esce
":wq" salva ed esce
"q!" si esce senza salvare
"/ + caratteri da cercare" per ricercare una stringa nel file. Entrati in modalita' ricerca, (/) per cercare la lettera dopo digitare "n"
"CTRL + G" da' le informazioni sul file
"? + caratteri da cercare" cerca i caratteri partendo dalla fine del file
": + n." della riga" ritorna alla riga desiderata
"G" ci si posiziona sull'ultima riga del file
"cw" cambia la parola
":s/parola da sostituire/parola che sostituisce" sostiusce una parola
":s/tutti/tutto/g" dove g sta per global
per modificare su tutto il file : 1;$s/xxx/yyy/g
Volendo si puo' salvare il file conun altro nome ":w nomefile", e cosi' le modifiche vengono salvate sul nuovo file
":r nomefile + invio" inserisce un altro file nel punto incui si trova il cursore


Tutti i processi quando girano, hanno una serie di variabili che sono quelle definite all'interno di un programma, inoltre hanno a disposizione un ambiente in cui gira il programma stesso "enviroment". Una delle variabili più utilizzate è la PATH che è quella che utilizza il sistema per cercare i programmi quando viene utilizzato il processo. Quanto gli script sono nella dir della PATH non vi sono problemi. Si richiama il contenuto delle variabili con il $.
MAILDIR = /var/mail
Quando la dobbiamo utilizzare, si usa il comando cd $MAILDIR.
Un'altra variabile di ambiente è la variabile HOME directory. Da qualsiasi punto si esegue:
cd $HOME.

Vi è un'altra variabile d'ambiente che si chiama MANPATH che server per vedere la manualistica del comando.

Il settaggio di una variabile d'ambiente dentro lo script avviene con la sintassi:

Se voglio richiamare il valore (contenuto) della variabile devo fare:

Dopo averla impostata, all'interno dello script essa si potrà utilizzare.Es.
In questo caso, usando una variabile d'ambiente, si cambia in automatico il nome di una directory.
Per rendere visibile la variabile ai processi figli bisogna usare il comando export NAME. Per eliminare la variabile d'ambiente utilizzare unset nome variabile.
Il comando env visualizza oltre alla PATH tutte le variabile di ambiente.

La variabile d'ambiente si può anche leggere fuori dallo script grazie al comando export NAME.
Quando la shell interpreta i comandi, vi è una sintassi: quando viene data in una stringa un comando la shell lo interpreta seguendo una sintassi precisa es.
$0; $1, etc,
echo $0
visualizza la parola pippo

Di seguito vi sono due tipi di file
il file seguente crea directory e file mediante variabili d'ambiente i cui nomi possono essere variati a piacere. (nome file: exe)

mkdir $NEWDIR
touch $FILE_1
mkdir $MYDIR
touch $FILE_2
cd ..
cd ..

Il file seguente è la creazione con spiegazioni (mediante il comando echo) di directories e files senza variabili d'ambiente.
(nome file: exe)

echo "creazione directory newdir"
read a
mkdir newdir
echo "entra in nredir"
read a
cd newdir
echo "ora creo il file myfile"
read a
touch myfile
echo "ora crea la direcory mydir"
read a
mkdir mydir
echo "ora entro in mydir"
read a
cd mydir
echo "ora crea il file file_2"
read a
touch file_2

Il seguente file cancella la struttura creata con l'opzione -r:
(nome file: cancella)
echo "cancella la struttura creata"
read a
rm -r newdir

Il seguente file cancella o crea alternativamente a seconda dell'esistenza o meno della struttura.
(nome file: test_dir)

if [ -d newdir ]
then cancella
else exe


grep mkdir nomefile
questo comando cerca una stringa all'interno di un file
grep -v mkdir nomefile fa il complemento di prima

identifica la mia linea di collegamento al server

visualizza i processi in esecuzione;
ps -ef (visualizza in profondità i processi in esecuzione)

Digitare etc /passwd
Editare il file.
A questo punto bisogna iniziare ad inserire gli utenti. Es.

Dalla Shell di vi si digita:

:r /tmp/pippo [invio]

Gestione della Posta in Unix

elm è uno dei client per la connessione al servizio di posta elettronica
appena digitato, il comando "elm" chiede di creare 2 dir: bisogna rispondere con "y" per due volte. Le dir saranno create in:

per visualizzare i processi in esecuzioni relativi alla propria utenza
ps -ef|grep nome_utente

come di configura la posta:
si configura il server per configurare la ns. posta SMTP. È il sereve al quale ci si rivolge per mandare la post in giro. POP3 invece è quello ove risiedono le caselle di posta. Nella macchina Unix SMTP è gia' attivo. Ne caselle di posta possiamo gia' scaricare la posta dal server.


tar -cvf [nome_file].tar *


tar -tvf [nome_archivio].tar


tar -xvf [nome_file].tar


make -f make.hpux10

Il file passwd che si trova all'interno della dir etc, (etc /passwd) contiene tutte i nomi degli appartenenti al gruppo.
La sintassi è:

nome_utente :: 102:20 ecc.ecc.ecc.

e si inseriscono tutti i nomi degli appartenenti al gruppo.

Nella riga dove c'è l'user, per poter accodare il contenuto di un file (all'interno di vi), la sintassi è la seguente:
:r /nome_file

sempre all'interno di vi, un altro comando per cercare tutti gli utenti:

grep ":20:" /etc/passwd
opzioni avanzate: grep ":20:" /etc/passwd |awk -F:

un'altra informazione:
la dir /tmp/ è usata per mettere files temporanei cancellabili.


Unix aspetta ad elaborare prima una parte del primo processo, poi passa al successivo.
Runnig Ò waiting
Tutta l'immagine del processo deve salvarla da qualche parte utilizzando una memoria virtuale: un'area su disco in cui il processore utilizza non per memorizzare i dati bensì per memorizzare queste istanze che stanno girando.
Prima c'è uno stato di waiting (quindi il processo rimane nella RAM). Non è detto che debba essere obbligatoriamente memorizzato su disco; in alternativa viene messo in uno stato di waiting swap.
Vi sono pero' degli stadi intermedi, atti a far si che il sistema operi in modo multitasking.
Un altro comando è:
che serve per vedere i processi in esecuzione

rsh serve per connettersi ad un'altra macchina:

in questo caso dal PC ti connetti al server

per i trasferimenti ricordiamo:
- ftp
- telnet

per visionare i comandi appenda eseguiti (spostandosi avanti e indietro) vi è un file che si chiama:
a questo punto digitando il tasto ESC + k si andrà in indietro, ESC + j si andrà in avanti.
Directory bin
Risiedono i files eseguibili.

Col comando cc (che è il compilatore che gira sotto Unix per compilare i files eseguibili) seguito dal nome del programma. Il risultato sarà un file col nome di default a.out. da comand line se voglio che esca con un altro nome devo aggiungere l'opzione -o + spezio + nome del file che voglio ottenere. Es:
cc nome_prg Ò a.out
cc(spazio)-o(spazio)nome che voglio mettere io(spazio)nome_prg Ònome che voglio mettere io (quest'ultimo sarà il nome del file compilato col nome che ho scelto)

con l'opzione cc -c (il file è compilato ma non è eseguibile) es.
cc -c pgm.c il file che ne uscirà sarà pgm.o (non eseguibile perché è un codice oggetto). Si evita la fase di link.

Nel make file si può specificare tutti i passi di compilazione a seconda della datazione dei files da compilare.es:
make -f nome_file


Risiedono i files sorgenti:
.c (file C++)
.h (header files )
spesso si trovano i make file, che sono file che aiutano nella compilazione, in essi vi sono i comandi da dare per compilare i files.

qui vi sono delle librerie che contengono tutti i file oggetto che servono ad esempio per gestire un database;

vi sono un sacco di comandi che servono per l'amministrazione die sistema;

vi sono degli special files per gestire le periferiche

You shouldn't concern yourself with becoming a FreeBSD UNIX guru to manage your Virtual Private Servers, you simply need a basic knowledge of a few easy-to-use UNIX commands. This list is by no means comprehensive, but it should be enough to get you started.

cd | pwd | ls | cat | mkdir | rmdir | cp | mv | rm | grep | tar | zip | unzip | compress | uncompress
cd [directory]
The cd command changes your current working directory to the directory you specify.
DOS Equivalent: cd

pwd The pwd command prints your current (or present) working directory.
Usage: Simply type pwd and hit return to display your current working directory.

ls [directory]
The ls command lists the files and subdirectories in the directory you specify. If no directory is specified, a list of the files and subdirectories in the current working directory is displayed.
Usage: The ls command will display all files in the current working directory - simply type ls and hit return. You can also add some additional arguments to customize the list display.
If you type ls -F it will append a forward slash to the subdirectory names so you can easily distinguish them from file names.
If you type ls -a it will show all hidden files. Hidden files begin with a dot (.), such as .htaccess files.
If you type ls -l it will show detailed information about each file and directory, including permissions, ownership, file size, and when the file was last modified.
You can also mix the arguments. If you type ls -aF you will see a list of all file names (including hidden files) and a forward slash will be appended to directory names.
DOS Equivalent: dir

cat [filename]
The cat command displays the contents of the filename you specify. If you want to display the file one screen at a time try cat [filename] | more or simply more [filename] (you may have done this at a DOS prompt- type [filename] | more).
DOS Equivalent: type

mkdir [directory]
The mkdir command makes a new directory with the name, directory, that you specify. Simply type mkdir [directory name] and hit return.
DOS Equivalent: md or mkdir

rmdir [directory]
The rmdir command removes the directory that you specify. Simply type rmdir [directory name] and hit return.
DOS Equivalent: rd or rmdir

cp [source-file] [target-file]
The cp command copies a source-file to a target-file. Simply type cp [source-file] [target-file] and hit return. You can specify pathnames as part of the file specification. If target-file exists it is overwritten.
DOS Equivalent: copy

mv [source-file] [target-file]
The mv command renames a file or moves it to a new location. Simply type mv [source-file] [target-file] and hit return. You can specify pathnames as part of the file specification. If target-file exists it is overwritten.
DOS Equivalent: rename

rm [filename]
The rm command deletes (removes) a file. Simply type rm [filename] and hit return. You can specify pathnames as part of the file specification.
DOS Equivalent: del

grep [pattern] [filenames]
The grep command finds lines in files that match specified text patterns. Simply type grep [pattern] [filenames] and hit return. You can specify pathnames as part of the file specification. For example if you want to search for the pattern gif in all html files in your current working directory, you would type grep gif *.html and hit return. The grep command would then list all occurrences of gif it finds in .html files in the current working directory.
DOS Equivalent: find

tar [options] [tarfile] [files]
The tar command copies a file or files to or from an archive. To put all the files in a directory into one tar format file, simply type tar -cvf tarfile directory at a telnet command prompt and replace tarfile with the name you want to call your archived file, and replace directory with the name of the directory that contains the files you want to compress.
To extract the files from a tar format archive, simply type tar -xvf tarfile at a telnet command prompt and replace tarfile with the name of the archived file you are extracting.
For example, you could type tar -cvf pages.tar htdocs at a telnet command prompt to archive the files in the htdocs directory to a tar format file called pages.tar.
To view the contents of the pages.tar tarfile without extracting them, type tar -tvf pages.tar. This will display all files that are included in the tar archive.
You could also type tar -xvf pages.tar at a telnet command prompt to extract into the current directory the files in the archive pages.tar.

zip [options] [zipfile] [files]
The zip command compresses a file or list of files into a zip format archive file. This command is compatible with pkzip on a PC. Simply type zip zipfile file1 file2 file3 at a telnet command prompt and replace zipfile with the name you want to use for your compressed zip archive file, and replace fileX with the name of the file(s) you want to compress into the zip archive.
For example, type zip backup.zip home.html index.html at a telnet command prompt to compress and archive the files called home.html and index.html into the file called backup.zip.
DOS Equivalent: pkzip

unzip [options] [zipfile]
The unzip command extracts a zip format archive file. This command is compatible with pkunzip files from a PC. Simply type unzip zipfile at a telnet command prompt and replace zipfile with the name of your zip format archive file.
For example, type unzip -aL old.zip at a telnet command prompt to extract files contained in the archive called old.zip. The -aL are options that are generally useful when unzipping files created on a PC.
DOS Equivalent: pkunzip

compress [files]
The compress command shrinks a file or files into compressed versions to save space on your Virtual Private Servers. This command is good for you to use on your log files when they get very large. Simply type compress filename(s) at a telnet command prompt and replace filename(s) with the name of your files you want to compress.
For example, type compress access_log agent_log at a telnet command prompt to compress the access_log and agent_log files. The compressed files will then be access_log.Z and agent_log.Z.

uncompress [files]
The uncompress command expands a compressed file or set of compressed files. Simply type uncompress filename(s) and hit return.

If you would like to know more about a particular command, you can consult the online manual page (manpage) by connecting to your Virtual Private Server via Telnet or SSH and issuing the following command.


Changes the directory.
SYNTAX: cd [directory Name user wishes to enter]

cd .. Used to go back one directory on the majority of all UNIX shells. It is important that the space be between the cd and the ..
cd - When in a Korn shell to get back one directory used to go back one directory.

cd hope - would go into the hope directory.
cd ../home/users/computerhope - would go back one directory and then go into the home/users/computerhope directory.
cd ../../ - would go back two directories.


Lists the contents of a directory.
SYNTAX: ls [-a] [-A] [-b] [-c] [-C] [-d] [-f] [-F] [-g] [-i] [-l] [-L] [-m] [-o] [-p] [-q] [-r] [-R] [-s] [-t] [-u] [-x] [pathnames]

-a Shows you all files, even files that are hidden (these files begin with a dot.)
-A List all files including the hidden files. However does not display the working directory (.) or the parent directory (..).
-b Force printing of non-printable characters to be in octal \ddd notation.
-c Use time of last modification of the i-node (file created, mode changed, and so forth) for sorting (-t) or printing (-l or -n).
-C Multi-column output with entries sorted down the columns. Generally this is the default option.
-d If an argument is a directory it only lists its name not its contents.
-f Force each argument to be interpreted as a directory and list the name found in each slot. This option turns off -l, -t, -s, and -r, and turns on -a; the order is the order in which entries appear in the directory.
-F Mark directories with a trailing slash (/), doors with a trailing greater-than sign (>), executable files with a trailing asterisk (*), FIFOs with a trailing vertical bar (|), symbolic links with a trailing at-sign (@), and AF_UNIX address family sockets with a trailing equals sign (=).
-g Same as -l except the owner is not printed.
-i For each file, print the i-node number in the first column of the report.
-l Shows you huge amounts of information (permissions, owners, size, and when last modified.)
-L If an argument is a symbolic link, list the file or directory the link references rather than the link itself.
-m Stream output format; files are listed across the page, separated by commas.
-n The same as -l, except that the owner's UID and group's GID numbers are printed, rather than the associated character strings.
-o The same as -l, except that the group is not printed.
-p Displays a slash ( / ) in front of all directories.
-q Force printing of non-printable characters in file names as the character question mark (?).
-r Reverses the order of how the files are displayed.
-R Includes the contents of subdirectories.
-s Give size in blocks, including indirect blocks, for each entry.
-t Shows you the files in modification time.
-u Use time of last access instead of last modification for sorting (with the -t option) or printing (with the -l option).
-x Displays files in columns.
-1 Print one entry per line of output.
pathnames File or directory to list.

ls -l
In the above example this command would list each of the files in the current directory and the files permissions, the size of the file, date of the last modification, and the file name or directory.

Copies files.
SYNTAX:cp [-i] [-r] oldfiles directory[/newfiles]
-i Prompts you before replacing a file.
-r When a directory is copied it copies the subdirectories within the directory and creates the directories if they do not exist.
oldfiles The file that you want to copy.
directory The name to give to a new copy.
newfiles The directory of were the new files are going to be.

cp file1.txt newdir - Copies the file1.txt to the newdir directory.
Many new versions of Unix or variants may also be able to use copy in place of cp or have a alias setup for cp as copy.

Renames a file or moves it from one directory to another directory.

mv [-f] [-i] oldname newname

-f mv will move the file(s) without prompting even if it is writing over an existing target. Note that this is the default if the standard input is not a terminal.
-i Prompts before overwriting another file.
oldname The oldname of the file renaming.
newname The newname of the file renaming.
filename The name of the file you want to move directory - The directory of were you want the file to go.

mv myfile.txt newdirectory/ - moves the file myfile.txt to the directory newdirectory.
mv myfile.txt ../ - moves the file myfile.txt back one directory (if available).


Deletes a file without confirmation (by default).

rm [-f] [-i] [-R] [-r] [filenames | directory]

-f Remove all files (whether write-protected or not) in a directory without prompting the user. In a write-protected directory, however, files are never removed (whatever their permissions are), but no messages are displayed. If the removal of a write-protected directory is attempted, this option will not suppress an error message.
-i Interactive. With this option, rm prompts for confirmation before removing any files. It over- rides the -f option and remains in effect even if the standard input is not a terminal.
-R Same as -r option.
-r Recursively remove directories and subdirectories in the argument list. The directory will be emptied of files and removed. The user is normally prompted for removal of any write-protected files which the directory contains. The write-protected files are removed without prompting, however, if the -f option is used, or if the standard input is not a terminal and the -i option is not used. Symbolic links that are encountered with this option will not be traversed. If the removal of a non-empty, write-protected directory is attempted, the utility will always fail (even if the -f option is used), resulting in an error message.
filenames A path of a filename to be removed.

rm myfile.txt - would remove the file myfile.txt without prompting the user.
rm -r directory - would remove a directory, even if files existed in that directory.

Changes the permission of a file.

chmod [-r] permissions filenames
-r Change the permission on files that are in the subdirectories of the directory that you are currently in.
permission Specifies the rights that are being granted. Below is the different rights that you can grant in alpha an numeric format.
filenames File or directory that you are associating the rights with.
u - User who owns the file.
g - Group that owns the file.
o - Other.
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.

Numeric Permissions:
CHMOD can also to attributed by using Numeric Permissions:

400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody

CHMOD 777 >> tutti i diritti
The above numeric Permissions can be added to set a certain permission for example a common HTML file on a UNIX server to be only viewed over the Internet would be:

CHMOD 755 file.htm

Which would be the following 400+040+004+200+020+100+010+001 = 775 where you are giving all the rights but the capability for anyone to edit your file.htm.


Below is an example of how a file may be listed when typing ( ls -l ) at the prompt as well as information on how to interpret it.

-rw-rw-r-- 1 hope 123 Feb 03 15:36 file.txt

- rw rw- r-- 1 hope 123 Feb 03 15:36 file.txt
File owner group everyone else links owner size mod date file name


cd >> vai sulla root
vi .profile >> vedi quale è la root
cd /etc >> cartella dove sta passwd >> vi passwd

Simple and very easy to use text editor in the style of the Pine Composer.

pico [+n] [-b] [-d] [-e] [-f] [-h] [-j] [-g] [-k] [-m] [-nn] [-] [-] [ file ]

+n Causes pico to be started with the cursor located n lines into the file. (Note: no space between "+" sign and number)
-b Enable the option to Replace text matches found using the "Where is" command.
-d Rebind the "delete" key so the character the cursor is on is rubbed out rather than the character to its left.
-e Enable file name completion.
-f Use function keys for commands. This option supported only in conjunction with UW Enhanced NCSA telnet.
-h List valid command line options.
-j Enable "Goto" command in the file browser. This enables the command to permit explicitly telling pilot which directory to visit.
-g Enable "Show Cursor" mode in file browser. Cause cursor to be positioned before the current selection rather than placed at the lower left of the display.
-k Causes "Cut Text" command to remove characters from the cursor position to the end of the line rather than remove the entire line.
-m Enable mouse functionality. This only works when pico is run from within an X Window System "xterm" window.
-nn The -nn option enables new mail notification. The n argument is optional, and specifies how often, in seconds, your mailbox is checked for new mail. For example, -n60 causes pico to check for new mail once every minute. The default interval is 180 seconds, while the minimum allowed is 30. (Note: no space between "n" and the number)
-o dir Sets operating directory. Only files within this directory are accessible. Likewise, the file browser is limited to the specified directory subtree.
-rn Sets column used to limit the "Justify" command's right margin
-s speller Specify an alternate program spell to use when spell checking.
-t Enable "tool" mode. Intended for when pico is used as the editor within other tools (e.g., Elm, Pnews). Pico will not prompt for save on exit, and will not rename the buffer during the "Write Out" command.
-v View the file only, disallowing any editing.
-w Disable word wrap (thus allow editing of long lines).
-x Disable keymenu at the bottom of the screen.
-z Enable ^Z suspension of pico.
-q Termcap or terminfo definition for input escape sequences are used in preference to sequences defined by default. This option is only available if pico was compiled with the TERMCAP_WINS define turned on.
-file The name of the file that you wish to edit.

pico myfile.txt - would open the editor with the file myfile.txt if present.

Note: when editing files, lines that are longer then the screen can display will end with a $. Move the cursor over will allow you to display the remainder of the line
When a running pico is disconnected, pico will save the current work if needed before exiting. Work is saved under the current filename with ".save" appended. If the current work is unnamed, it is saved under the filename "pico.save".


Clears the screen

clear - would clear the screen.

Many newer UNIX systems and Unix variants will also accept the CLS command or have CLS as an alias for clear.

Short for print working directory the pwd command displays the name of the current working directory.


pwd - Typing pwd at the prompt would give you something similar to:


Pine is a program for Internet News and Email

pine [option] [address , address]
pinef [option] [address , address]

address Send mail to address this will open pine directly into the message composer.
-a Special anonymous mode for UWIN.
-attach file Send e-mail with the selected file as an attachment.
-attach_and_delete file Send e-mail with the selected file as an attachment and remove file after sent.
-attach file-list Send e-mail with the listed file-list as an attatchment.
-c context-number context-number is the number corresponding to the folder-collection to which the -f command line argument should be applied. By default the -f argument is applied to the first defined folder collection.
-d debug-level Output diagnostic info at debug-level (0-9) to the current .pine-debug[1-4] file. A value of 0 turns debugging off and suppresses the .pine-debug file.
-d key[=val] Fine tuned output of diagnostic messages where "flush" causes debug file writing without buffering, "timestamp" appends each message with a timestamp, "imap=n" where n is between 0 and 4 representing none to verbose IMAP telemetry reporting, "numfiles=n" where n is between 0 and 31 corresponding to the number of debug files to maintain, and "verbose=n" where n is between 0 and 9 indicating an inverse threshold for message output.
-f folder Open folder (in first defined folder collection, use -c n to specify another collection) instead of INBOX.
-F file Open named text file and view with Pine's browser.
-h Help: list valid command-line options.
-i Start up in the FOLDER INDEX screen.
-I keystrokes Initial (comma separated list of) keystrokes which Pine should execute on startup.
-k Use function keys for commands. This is the same as running the command pinef.
-n number Start up with current message-number set to number.
-nr Special mode for UWIN.
-o Open first folder read-only.
-p config_file Use config-file as the personal configuration file instead of the default .pinerc.
-P config_file Use config-file as the configuration file instead of default system-wide configuration file pine.conf.
-r Use restricted/demo mode. Pine will only send mail to itself and functions like save and export are restricted.
-url url Open the given url. Cannot be used with -f, -F, or -attach options.
-z Enable ^Z and SIGTSTP so pine may be suspended.
-conf Produce a sample/fresh copy of the system-wide configuration file, pine.conf, on the standard output. This is distinct from the per-user .pinerc file.
-create_lu addrbook sort-order Creates auxiliary index (look-up) file for addrbook and sorts addrbook in sort-order, which may be dont-sort, nickname, fullname, nickname-with- lists-last, or fullname-with-lists-last. Useful when creating global or shared address books. After creating the index file in this way, the file should be moved or copied in a way which preserves the mtime of the address book file. The mtime of the address book file at the
time the index file was built is stored inside the index file and a comparison
between that stored value and the current mtime of the address book file is done when somebody runs pine. If the mtime has changed since the index file was made, then pine will want to rebuild the index file. In other words, don't build the index file with this option
and then copy the address book to its final destination in a way which changes the file's mtime.
-pinerc file Output fresh pinerc configuration to file.
-sort order Sort the FOLDER INDEX display in one of the following orders: arrival, subject, from, date, size, orderedsubj or reverse. Arrival order is the default. The OrderedSubj choice simulates a threaded sort. Any sort may be reversed by adding /reverse to it. Reverse by
itself is the same as arrival/reverse.
-option=value Assign value to the config option option e.g. -signature-file=sig1 or -feature-
list=signature-at-bottom (Note: feature-list values are additive)

Below is a general listing of files related to mail and pine on a UNIX or UNIX variant system:

/usr/spool/mail/xxxx Default folder for incoming mail.
~/mail Default directory for mail folders.
~/.addressbook Default address book file.
~/.addressbook.lu Default address book index file.
~/.pine-debug[1-4] Diagnostic log for debugging.
~/.pinerc Personal pine config file.
~/.newsrc News subscription/state file.
~/.signature Default signature file.
~/.mailcap Personal mail capabilities file.
~/.mime.types Personal file extension to MIME type mapping
/etc/mailcap System-wide mail capabilities file.
/etc/mime.types System-wide file ext. to MIME type mapping
/usr/local/lib/pine.info Local pointer to system administrator.
/usr/local/lib/pine.conf System-wide configuration file.
/usr/local/lib/pine.conf.fixed Non-overridable configuration file.
/tmp/.\usr\spool\mail\xxxx Per-folder mailbox lock files.
~/.pine-interrupted-mail Message which was interrupted.
~/mail/postponed-msgs For postponed messages.
~/mail/sent-mail Outgoing message archive (FCC).
~/mail/saved-messages Default destination for Saving messages.

pine - would run the pine program


Create tape archives and add or extract files

tar c [ bBeEfFhiklnopPqvwX [ 0-7 ] ] [ block ] [ tarfile ] [ exclude-file ] {-I include-file | -C directory | file | file }
tar r [ bBeEfFhiklnqvw [ 0-7 ] ] [ block ] {-I include-file | -C directory | file | file }
tar t [ BefFhiklnqvX [ 0-7 ] ] [ tarfile ] [ exclude-file ] {-I include-file | file } ...
tar u [ bBeEfFhiklnqvw [ 0-7 ] ] [ block ] [ tarfile ] file ...
tar x [ BefFhiklmnopqvwX [ 0-7 ] ] [ tarfile ] [ exclude-file ] [ file ... ]

c Create. Writing begins at the beginning of the tarfile, instead of at the end.
r Replace. The named file s are written at the end of the tarfile. A file created with extended headers must be updated with extended headers (see E flag under Function Modifiers). A file created without extended headers cannot be modified with extended headers.
t Table of Contents. The names of the specified files are listed each time they occur in the tar file. If no file argument is given, the names of all files in the tarfile are listed. With the v
function modifier, additional information for the specified files is displayed.
u Update. The named file s are written at the end of the tarfile if they are not already in the tar file, or if they have been modified since last written to that tarfile. An update can be rather slow. A tarfile created on a 5.x system cannot be updated on a 4.x system. A file created with extended headers must be updated with extended headers (see E flag under Function Modifiers). A file created without extended headers cannot be modified with extended headers.
x Extract or restore. The named file s are extracted from the tarfile and written to the directory specified in the tarfile, relative to the current directory. Use the relative path names of files and directories to be extracted. If a named file matches a directory whose contents has been writ ten to the tarfile, this directory is recursively extracted. The owner, modification time, and mode are restored (if possible); otherwise, to restore owner, you must be the super-user. Character special and block-special devices (created by mknod(1M)) can only be extracted by the super user. If no file argument is given, the entire content of the tarfile is extracted. If the tar- file contains several files with the same name, each file is written to the appropriate directory, overwriting the previous one. Filename substitu tion wildcards cannot be used for extracting files from the archive; rather, use a command of the form:
tar xvf... /dev/rmt/0 `tar tf... /dev/rmt/0 | grep 'pattern' `

When extracting tapes created with the r or u functions, directory modification times may not be set correctly. These same functions cannot be used with many tape drives due to tape drive limitations such as the absence of backspace or append capabilities.

When using the r, u, or x functions or the X function modifier, the named files must match exactly the corresponding files in the tarfile. For example, to extract ./thisfile, you must specify ./thisfile, and not thisfile. The t function displays how each file was archived.

Function Modifiers
The characters below may be used in conjunction with the letter that selects the desired function.
b Blocking Factor. Use when reading or writing to raw magnetic archives (see f below). The block argument specifies the number of 512-byte tape blocks to be included in each read or write operation performed on the tarfile. The minimum is 1, the default is 20. The maximum value is a function of the amount of memory available and the blocking requirements of the specific tape device involved (see mtio(7I) for details.) The maximum cannot exceed INT_MAX/512 (4194303).
When a tape archive is being read, its actual blocking factor will be automatically detected, provided that it is less than or equal to the nominal blocking factor (the value of the block argument, or the default value if the b modifier is not specified). If the actual blocking factor is greater than the nominal blocking factor, a read error will result. See Example 5 in EXAMPLES.

B Block. Force tar to perform multiple reads (if necessary) to read exactly enough bytes to fill a block. This function modifier enables tar to work across the Ethernet, since pipes and sockets return partial blocks even when more data is coming. When reading from standard input, '-', this function modifier is selected by default to ensure that tar can recover from short reads.
e Error. Exit immediately with a positive exit status if any unexpected errors occur. The SYSV3 environment variable overrides the default behavior. (See ENVIRONMENT section below.)
E Write a tarfile with extended headers. (Used with c, r, or u options; ignored with t or x options.) When a tarfile is written with extended headers, the modification time is maintained with a granularity of microseconds rather than seconds. In addition, filenames no longer than PATH_MAX characters that could not be archived without E, and file sizes greater than 8GB, are supported. The E flag is required whenever the larger files and/or files with longer names, or whose UID/GID exceed 2097151, are to be archived, or if time granularity of microseconds is desired.
f File. Use the tarfile argument as the name of the tarfile. If f is specified, /etc/default/tar is
not searched. If f is omitted, tar will use the device indicated by the TAPE environment variable, if set; otherwise, it will use the default values defined in /etc/default/tar. If the name of the tarfile is '-', tar writes to the standard output or reads from the standard input, whichever is appropriate. tar can be used as the head or tail of a pipeline. tar can also be used to move hierarchies with the command:
example% cd fromdir; tar cf - .| (cd todir; tar xfBp -)

F With one F argument, tar excludes all directories named SCCS and RCS from the tarfile. With two arguments, FF, tar excludes all directories named SCCS and RCS, all files with .o as their suffix, and all files named errs, core, and a.out. The SYSV3 environment variable overrides the default behavior. (See ENVIRONMENT section below.)
h Follow symbolic links as if they were normal files or directories. Normally, tar does not follow symbolic links.
i Ignore directory checksum errors.
k size Requires tar to use the size argument as the size of an archive in kilobytes. This is useful when the archive is intended for a fixed size device such as floppy disks. Large files are then split across volumes if they do not fit in the specified size.
l Link. Output error message if unable to resolve all links to the files being archived. If l is not specified, no error messages are printed.
m Modify. The modification time of the file is the time of extraction. This function modifier is
valid only with the x function.
n The file being read is a non-tape device. Reading of the archive is faster since tar can randomly seek around the archive.
o Ownership. Assign to extracted files the user and group identifiers of the user running the program, rather than those on tarfile. This is the default behavior for users other than root. If the o function modifier is not set and the user is root, the extracted files will take on the group and user identifiers of the files on tarfile (see chown for more information). The o function modifier is only valid with the x function.
p Restore the named files to their original modes, and ACLs if applicable, ignoring the present umask. This is the default behavior if invoked as super-user with the x function letter specified. If super-user, SETUID and sticky information are also extracted, and files are restored with their original owners and permissions, rather than owned by root. When this function modifier is used with the c function, ACLs are created in the tarfile along with other information. Errors will occur when a tarfile with ACLs is extracted by
previous versions of tar .
P Suppress the addition of a trailing "/" on directory entries in the archive.
q Stop after extracting the first occurrence of the named file. tar will normally continue reading the archive after finding an occurrence of a file.
v Verbose. Output the name of each file preceded by the function letter. With the t function, v provides additional information the tarfile entries. The listing is similar to the format produced by the -l option of the ls command.
w What. Output the action to be taken and the name of the file, then await the user's confirmation. If the response is affirmative, the action is performed; otherwise, the action is not performed. This function modifier cannot be used with the t function.
X Exclude. Use the exclude-file argument as a file containing a list of relative path names for files (or directories) to be excluded from the tarfile when using the functions c, x, or t. Be careful of trailing white spaces. Also beware of leading white spaces, since, for each line in the excluded file, the entire line (apart from the newline) will be used to match against the initial string of files to exclude. Multiple X arguments may be used, with one exclude-file per argument. In the case where included files (see -I include-file option) are also specified, the excluded files take precedence over all included files. If a file is specified in both the exclude-file and the include-file (or on the command line), it will be excluded.
[0-7] Select an alternative drive on which the tape is mounted. The default entries are specified in /etc/default/tar. If no digit or f function modifier is specified, the entry in /etc/default/tar with digit "0" is the default.
-I include-file Opens include-file containing a list of files, one per line, and treats it as if each file appeared separately on the command line. Be careful of trailing white spaces. Also beware of leading white spaces, since, for each line in the included file, the entire line (apart from the newline) will be used to match against the initial string of files to include. In the case where excluded files (see X function modifier) are also specified, they take precedence over all included files. If a file is specified in both the exclude-file and the include-file (or on the command line), it will be excluded.

Remainder Syntax

-C directory file Performs a chdir (see cd(1)) operation on directory and performs the c (create) or r (replace) operation on file . Use short relative path names for file . If file is `.', archive all files in directory. This option enables archiving files from multiple directories not related by a close common parent.
file A path name of a regular file or directory to be archived (when the c, r or u functions are specified), extracted (x) or listed (t). When file is the path name of a directory, the action applies to all of the files and (recursively) subdirectories of that directory.
When a file is archived, and the E flag (see Function Modifiers) is not specified, the filename cannot exceed 256 characters. In addition, it must be possible to split the name between parent directory names so that the prefix is no longer than 155 characters and the name is no longer than 100 characters. If E is specified, a name of up to PATH_MAX characters may be specified.

For example, a file whose basename is longer than 100 characters could not be archived without using the E flag. A file whose directory portion is 200 characters and whose basename is 50 characters could be archived (without using E) if a slash appears in the directory name somewhere in character positions 151-156.

Compressing (tar) a file:
tar -cvvf file.tar myfile.txt
In the above example the system would create a tar named file.tar in the directory you currently are in. Wildcards could also be used in this command, for example: tar -cvvf file.tar *.txt would compress all txt files in the current directory.

tar -cvvf home.tar home/
In the above example command the system would create a tar file named home.tar in the directory you currently are in of the home directory.

Uncompressing (untar) a file:

tar -xvvf myfile.tar
In the above example command the system would uncompress (untar) the myfile.tar file in the current directory.

tar -xvvzf myfile.tar.gz
In the above example command the system would uncompress (untar) the myfile.tar.gz file in the current direcotry.

Note: There is no "untar" linux / unix command.


Finds one or more files assuming that you know their approximate filenames.

find path expressions

path A path name of a starting point in the directory hierarchy.
-atime n True if the file was accessed n days ago. The access time of directories in path is changed by find itself.
-cpio device Always true; write the current file on device in cpio format (5120-byte records).
-ctime n True if the file's status was changed n days ago.
-depth Always true; causes descent of the directory hierarchy to be done so that all entries in a directory are acted on before the directory itself. This can be useful when find is used with cpio to transfer files that are contain edin directories without write permission.
-exec command True if the executed command returns a zero value as exit status. The end of command must be punctuated by an escaped semicolon. A command argument {} is replaced by the current path name.
-follow Always true; causes symbolic links to be followed. When following symbolic links, find keeps track of the directories visited so that it can detect infinite loops; for example, such a loop would occur if a symbolic link pointed to an ancestor. This expression should not be used with the -type l expression.
-fstype type True if the filesystem to which the file belongs is of type type .
-group gname True if the file belongs to the group gname. If gname is numeric and does not appear in the /etc/group file, it is taken as a group ID.
-inum n True if the file has inode number n.
-links True if the file has n links.
-local True if the file system type is not a remote file system type as defined in the /etc/dfs/fstypes file. nfsis used as the default remote filesystem type if the/etc/dfs/fstypes file is not present.
-ls Always true; prints current path name together
with its associated statistics. These include
inode number
size in kilobytes (1024 bytes)
protection mode
number of hard links
size in bytes
modification time.
If the file is a special file the size field will instead contain the major and minor device numbers.

If the file is a symbolic link the pathname of the linked-to file is printed preceded by `->'. The format is identical to that of ls -gilds ls Note: Formatting is done internally, without executing the ls program.

-mount Always true; restricts the search to the file system containing the directory specified. Does not list mount points to other file systems.
-mtime n True if the file's data was modified n days ago.
-name pattern True if pattern matches the current file name. Normal shell file name generation characters (see sh) may be used. A backslash (\) is used as an escape character within the pattern. The pattern should be escaped or quoted when find is invoked from the shell.
-ncpio device Always true; write the current file on device in cpio -c format (5120 byte records).
-newer file True if the current file has been modified more recently than the argument file.
-nogroup True if the file belongs to a group not in the /etc/group file.
-nouser True if the file belongs to a user not in the /etc/passwd file.
-ok command Like -exec except that the generated command line is printed with a question mark first, and is executed only if the user responds by typing y.
-perm [-]mode The mode argument is used to represent file mode bits. It will be identical in format to the operand described in chmod, and will be interpreted as follows. To start, a template will be assumed with all file mode bits cleared. An op symbol of:

+ will set the appropriate mode bits in the template;
- will clear the appropriate bits;
= will set the appropriate mode bits, without regard to the contents of process' file mode creation mask.

The op symbol of - cannot be the first character of mode; this avoids ambiguity with the optional leading hyphen. Since the initial mode is all bits off, there are not any symbolic modes that need to use - as the first character.

If the hyphen is omitted, the primary will evaluate as true when the file permission bits exactly match the value of the resulting template.

Otherwise, if mode is prefixed by a hyphen, the primary will evaluate as true if at least all the bits in the resulting template are set in the file permission bits.

-perm [-]onum True if the file permission flags exactly match the octal number onum see chmod). If onum is prefixed by a minus sign (-), only the bits that are set in onum are compared with the file permission flags, and the expression evaluates true if they match.
-print Always true; causes the current path name to be printed.
-prune Always yields true. Do not examine any directories or files in the directory structure below the pattern just matched. If -depth is specified, -prune will have no effect.
-size n[c] True if the file is n blocks long (512 bytes per block). If n is followed by a c, the size is in
-type c True if the type of the file is c, where c is b, c, d, D, f, l, p, or s for block special file, character special file, directory, door, plain file, symbolic link, fifo (named pipe), or socket, respectively.
-user uname True if the file belongs to the user uname . If uname is numeric and does not appear as a login name in the /etc/passwd file, it is taken as a user ID.
-xdev Same as the -mount primary.

When using find to determine files modified within a range of time, one must use the ?time argument before the -print argument; otherwise, find will give all files.

find -name 'mypage.htm'
In the above command the system would search for any file named mypage.htm in the current directory and any subdirectory.
find / -name 'mypage.htm'
In the above example the system would search for any file named mypage.htm on the root and all subdirectories from the root.
find -name 'file*'
In the above example the system would search for any file beginning with file in the current directory and any subdirectory.
find -name '*' -size +1000k
In the above example the system would search for any file that is larger then 1000k.


Finds text within a file.

grep [-b] [-c] [-h] [-i] [-l] [-n] [-s] [-v] [-w] text filenames

-b Precede each line by the block number on which it was found. This can be useful in locating block
-c Print only a count of the lines that contain the pattern.
-h Prevents the name of the file containing the matching line from being appended to that line. Used when searching multiple files.
-i Ignores case.
-l Displays the files that have the text not the text within the file.
-n Precede each line by its line number in the file (first line is 1).
-s Suppress error messages nonexistent or unreadable files.
-v Specifies you are looking for files that don't contain the text.
-w Search for the expression as a word as if surrounded by \< and \>.
text The text that you are searching / not searching for. See also below patterns.
filenames the name of the file that you are searching in.

Kinds of Patterns for searching.
. Matches single character.
* Wild character Example C* if found would pull up CC or CAT...
{} Matches any character contained within the bracket.
^ Represents the beginning of the line, so if you did ^T it would search for any sentence starting with a T.
$ Represents the end of the line, so if you did $. then it would pull up any lines that ended with .
\ Means to take the next character serious so you could search for C\ C.

Note: Be careful using the characters $, *, [, ^, |, (, ), and \ in the pattern list because they are also meaningful to the shell. It is safest to enclose the entire pattern list in single quotes '... '.

grep "unix" *.htm - Would search all .htm files in the current directory for any reference of unix and give results similar to the follow:

asoftwar.htm: href="win95.htm">Windows 95, Unix, MS-DOS,
asoftwar.htm: UNIX
learnhtm.htm: Unix help

os.htm: UNIX

As illustrated above are you can see that grep has found references of unix in some of the HTML files in our home directory. The file which contains unix is listed before the line. For example asoftwar.htm is a name of our Software help page which as illustrated links to Unix.


Screen-oriented (visual) display editor based on ex.

vi [ -| -s ] [-l] [-L] [-R] [ -r [ filename ] ] [-S] [-t tag] [-v] [-V] [-x] [-w] [-n ] [-C] [+command | -c command ] filename

- | -s Suppress all interactive user feedback. This is useful when processing editor scripts.
-l Set up for editing LISP programs.
-L List the name of all files saved as the result of an editor or system crash.
-R Readonly mode; the readonly flag is set, preventing accidental overwriting of the file.
-r filename Edit filename after an editor or system crash. (Recovers the version of filename that was in the buffer when the crash occurred.)
-S This option is used in conjunction with the -t tag option to tell vi that the tags file may not be sorted and that, if the binary search (which relies on a sorted tags file) for tag fails to
find it, the much slower linear search should also be done. Since the linear search is slow, users of large tags files should ensure that the tags files are sorted rather than use this flag. Creation of tags files normally produces sorted tags files. See ctags for more information on tags files.
-t tag Edit the file containing the tag, tag, and position the editor at its definition.
-v Start up in display editing state using vi . You can achieve the same effect by simply typing the vi command itself.
-V Verbose. When ex commands are read by means of standard input, the input will be echoed to standard error. This may be useful when processing ex commands within shell scripts.
-x Encryption option; when used, vi simulates the X command of ex and prompts the user for a key. This key is used to encrypt and decrypt text using the algorithm of the crypt command. The X command makes an educated guess to determine whether text read in is encrypted or not. The temporary buffer file is encrypted also, using a transformed version of the key typed in for the -x option. If an empty encryption key is entered (that is, if the return key is pressed right after the prompt), the file will not be encrypted. This is a good way to decrypt a file erroneously encrypted with a mistyped encryption key, such as a backspace or undo key.
-wn Set the default window size to n. This is useful when using the editor over a slow speed line.
-C Encryption option; same as the -x option, except that vi simulates the C command of ex . The C command is like the X command of ex , except that all text read in is assumed to have been encrypted.
+command | -c command Begin editing by executing the specified editor
command (usually a search or positioning command).
filename The file to be edited.

Arrow keys Move cursor
hjkl Same as arrow keys
itextESC Insert text
cwnewESC Change word to new
easESC pluralize word (end of word; append s; escape from input state)
x delete a character
dw delete a word
dd delete a line
3dd deletes 3 lines
u undo previous change
ZZ exit vi , saving changes
:q!CR quit, discarding changes
/textCR search for text
^U ^D scroll up or down
:cmdCR any ex or ed command
ESC end insert or incomplete command
DEL (delete or rubout) interrupts
:wCR write back changes
:w!CR forced write, if permission originally not valid
:qCR quit
:q!CR quit, discard changes
:e nameCR edit file name
:e!CR reedit, discard changes
:e + nameCR edit, starting at end
:e +nCR edit, starting at line n
:e #CR edit alternate file
:e! #CR edit alternate file, discard changes
:w nameCR write file name
:w! nameCR overwrite file name
:shCR run shell, then return
:!cmdCR run cmd, then return
:nCR edit next file in arglist
:n argsCR specify new arglist
^G show current file and line
:ta tagCR position cursor to tag
F forward screen
^B backward screen
^D scroll down half screen
^U scroll up half screen
nG go to the beginning of the specified line (end default), where n is a line number
/pat next line matching pat
?pat previous line matching pat
n repeat last / or ? command
N reverse last / or ? command
/pat/+n nth line after pat
?pat?-n nth line before pat
]] next section/function
[[ previous section/function
( beginning of sentence
) end of sentence
{ beginning of paragraph
} end of paragraph
% find matching ( ) or { }
^L clear and redraw window
^R clear and redraw window if ^L is -> key
zCR redraw screen with current line at top of window
z-CR redraw screen with current line at bottom of window
z.CR redraw screen with current line at center of window
/pat/z-CR move pat line to bottom of window
zn.CR use n-line window
^E scroll window down one line
^Y scroll window up one line
`` move cursor to previous context
'' move cursor to first non-white space in line
mx mark current position with the ASCII lower-case letter x
`x move cursor to mark x
'x move cursor to first non-white space in line marked by x
H top line on screen
L last line on screen
M middle line on screen
+ next line, at first non-white space character
- previous line, at first non-white space character
CR return, same as +
down-arrow or j next line, same column
up-arrow or k previous line, same column
^ first non-white space character
0 beginning of line
$ end of line
l or -> forward
h or <- backward
^H same as <- (backspace)
space same as -> (space bar)
fx find next x
Fx find next x
tx move to character following the next x
Tx move to character following the previous x
; repeat last f, F, t, or T
, repeat inverse of last f, F, t, or T
n| move to column n
% find matching ( ) or { }
w forward a word
b back a word
e end of word
) to next sentence
} to next paragraph
( back a sentence
{ back a paragraph
W forward a blank-delimited word
B back a blank-delimited word
E end of a blank-delimited word
^H erase last character (backspace)
^W erase last word
erase your erase character, same as ^H (backspace)
kill your kill character, erase this line of input
\ quotes your erase and kill characters
ESC ends insertion, back to command mode
CTRL-C interrupt, suspends insert mode
^D backtab one character; reset left margin of autoindent
^^D caret (^) followed by control-d (^D); backtab to beginning of line; do not reset left margin of autoindent
0^D backtab to beginning of line; reset left margin of autoindent
^V quote non-printable character
a append after cursor
A append at end of line
i insert before cursor
I insert before first non-blank
o open line below
O open line above
rx replace single character with x
RtextESC replace characters
d delete
c change
y yank lines to buffer
> left shift
< right shift
! filter through command
C change rest of line (c$)
D delete rest of line (d$)
s substitute characters (cl)
S substitute lines (cc)
J join lines
x delete characters (dl)
X delete characters before cursor dh)
Y yank lines (yy)
3yy yank 3 lines
3yl yank 3 characters
p put back text after cursor
P put back text before cursor " .nr )I xp"n
put from buffer x " .nr )I xy"n
yank to buffer x " .nr )I xd"n
delete into buffer x
u undo last change
U restore current line
. repeat last change " .nr )I dp"n
retrieve d'th last delete

vi myfile.txt - Edits the file myfile.txt.


The "ifconfig" command allows the operating system to setup network interfaces and allow the user to view information the configured network interfaces.

ifconfig [-L] [-m] interface [create] [address_family] [address[/prefixlength] [dest_address]] [parameters]
ifconfig interface destroy
ifconfig -a [-L] [-d] [-m] [-u] [address_family]
ifconfig -l [-d] [-u] [address_family]
ifconfig [-L] [-d] [-m] [-u] [-C]

address For the DARPA-Internet family, the address is either a host name present in the host name data base, or a DARPA Internet address expressed in the Internet standard ``dot notation''.
It is also possible to use the CIDR notation (also known as the slash notation) to include the netmask. That is, one can specify an address like

addres_family Specify the address family which affects interpretation of the remaining parameters. Since an interface can receive transmissions in differing protocols with different naming schemes, specifying the address family is recommended. The address or protocol families currently supported are ``inet'', ``inet6'',
dest_address Specify the address of the correspondent on the other end of a point to point link.
interface This parameter is a string of the form ``name unit'', for example, ``en0''.
add Another name for the alias parameter. Introduced for compatibility with BSD/OS.
alias Establish an additional network address for this interface. This is sometimes useful when changing network numbers, and one wishes to accept packets addressed to the old interface. If the address is on the same subnet as the first network address for this interface, a netmask of 0xffffffff has to be specified.
-alias Remove the network address specified. This would be used if you incorrectly specified an alias, or it was no longer needed. If you have incorrectly set an NS address having the side effect of specifying the host portion, removing all NS addresses will allow you to respecify the host portion.
anycast (Inet6 only.) Specify that the address configured is an anycast address. Based on the current specification, only routers may configure anycast addresses. Anycast address will not be used as source address of any of outgoing IPv6 packets.
arp Enable the use of the Address Resolution Protocol in mapping between network level addresses and link level addresses (default). This is currently implemented for mapping between DARPA Internet addresses and IEEE 802 48-bit MAC addresses (Ethernet, FDDI, and Token Ring addresses).
-arp Disable the use of the Address Resolution Protocol
broadcast (Inet only.) Specify the address to use to represent broadcasts to the network. The default broadcast address is the address with a host part of all 1's.
debug Enable driver dependent debugging code; usually, this turns on extra console error logging.
-debug Disable driver dependent debugging code.
delete Another name for the -alias parameter.
down Mark an interface ``down''. When an interface is marked ``down'', the system will not attempt to transmit messages through that interface. If possible, the interface will be reset to disable reception as well. This action does not automatically disable routes using the interface.
ether Another name for the lladdr parameter.
lladdr addr Set the link-level address on an interface. This can be used to e.g. set a new MAC address on an ethernet interface, though the mechanism used is not ethernet-specific. The address addr is specified as a series of colon-separated hex digits. If the interface is already up when this option is used, it will be briefly brought down and then brought back up again in order to ensure that the receive filter in the underlying ethernet hardware is properly reprogrammed.
media type If the driver supports the media selection system, set the media type of the interface to type. Some interfaces support the mutually exclusive use of one of several different physical media connectors. For example, a 10Mb/s Ethernet interface might support the use of either AUI or twisted pair connectors. Setting the media type to ``10base5/AUI'' would change the currently active connector to the AUI port. Setting it to ``10baseT/UTP'' would activate twisted pair. Refer to the interfaces' driver specific documentation or man page for a complete list of the available types.
-mediaopt opts If the driver supports the media selection system, set the specified media options on the interface. The opts argument is a comma delimited list of options to apply to the interface. Refer to the interfaces' driver specific man page for a complete list of available options.
tunnel src_addr dest_addr (IP tunnel devices only.) Configure the physical source and destination address for IP tunnel interfaces. The arguments src_addr and dest_addr are interpreted as the outer source/destination for the encapsulating IPv4/IPv6 header.
deletetunnel Unconfigure the physical source and destination address for IP tunnel interfaces previously configured with tunnel.
create Create the specified network pseudo-device. If the interface is given without a unit number, try to create a new device with an arbitrary unit number. If creation of an arbitrary device is successful, the new device name is printed to standard output.
destroy Destroy the specified network pseudo-device.
plumb Another name for the create parameter. Included for Solaris compatibility.
unplumb Another name for the destroy parameter. Included for Solaris compatibility.
metric n Set the routing metric of the interface to n, default 0. The routing metric is used by the routing protocol. Higher metrics have the effect of making a route less favorable; metrics are counted as addition hops to the destination network or host.
mtu n Set the maximum transmission unit of the interface to n, default is interface specific. The MTU is used to limit the size of packets that are transmitted on an interface. Not all interfaces support setting the MTU, and some interfaces have range restrictions.
netmask mask (Inet only.) Specify how much of the address to reserve for subdividing networks into subnetworks. The mask includes the network part of the local address and the subnet part, which is taken from the host field of the address. The mask can be specified as a single hexadecimal number with a leading `0x', with a dot-notation Internet address, or with a pseudo-network name listed in the network table. The mask contains 1's for the bit positions in the 32-bit address which are to be used for the network and subnet parts, and 0's for the host part. The mask should contain at least the standard network portion, and the subnet field should be contiguous with the network portion. The netmask can also be specified in CIDR notation after the address. See the address option above for more information.
prefixlen len (Inet6 only.) Specify that len bits are reserved for subdividing networks into sub-networks. The len must be integer, and for syntactical reason it must be between 0 to 128. It is almost always 64 under the current IPv6 assignment rule. If the parameter is omitted, 64 is used.
remove Another name for the -alias parameter. Introduced for compatibility with BSD/OS.
link[0-2] Enable special processing of the link level of the interface. These three options are interface specific in actual effect, how- ever, they are in general used to select special modes of operation. An example of this is to enable SLIP compression, or to select the connector type for some Ethernet cards. Refer to the man page for the specific driver for more information.
-link[0-2] Disable special processing at the link level with the specified interface.
up Mark an interface ``up''. This may be used to enable an interface after an ``ifconfig down''. It happens automatically when setting the first address on an interface. If the interface was reset when previously marked down, the hardware will be re-initialized.

ifconfig eth0 - View the network settings on the first Ethernet adapter installed in the computer.


Tells you the date and time in UNIX.

date [-a] [-u] [-s datestr]

-a Slowly adjust the time by sss.fff seconds (fff represents fractions of a second). This adjustment can be positive or negative. The system's clock will be sped up or slowed down until it has drifted by the number of seconds specified. Only the super-user may adjust the time.
-u Display (or set) the date in Greenwich Mean Time (GMT-universal time), bypassing the normal conversion to (or from) local time.
-s datestr Sets the time and date to the value specfied in the datestr. The datestr may contain the month names, timezones, 'am', 'pm', etc. See examples for an example of how the date and time can be set.

date - Would list the date and time of the server. Below is an example of the output.
Thu Feb 8 16:47:32 MST 2001
date -s "11/20/2003 12:48:00" - Set the date to the date and time shown.
date '+DATE: %m/%d/%y%nTIME:%H:%M:%S' - Would list the time and date in the below format:

DATE: 02/08/01

If you are looking for additional information the release date of UNIX or a UNIX variant please see our main UNIX page or our history section.


Cancels a job.

kill [-s] [-l] %pid

-s Specify the signal to send, using one of the symbolic names defined in the description. Values of signal will be recognized in a case independent fashion, without the SIG prefix. In addition, the symbolic name 0 will be recognized, representing the signal value zero. The corresponding signal will be sent instead of SIGTERM.
-l Write all values of signal sup ported by the implementation, if no operand is given. If an exit_status operand is given and it is a value of the ? shell special parameter and wait corresponding to a process that was ter minated by a signal, the signal corresponding to the signal that terminated the process will be written. If an exit_status operand is given and it is the unsigned decimal integer value of a signal number, the signal corresponding to that signal will be written. Otherwise, the results are unspecified.
pid One of the following:
1. A decimal integer specifying a process or process group to be signaled. The process or processes selected by positive, negative and zero values of the pid operand will be as
described for the kill function. If process number 0 is specified, all processes in the process group are signaled. If the first pid operand is negative, it should be preceded by -- to keep it from being interpreted as an option.

2. A job control job ID that identifies a background process group to be signaled. The job control job ID notation is applicable only for invocations of kill in the current shell execution environment.

Note the job control job ID type of pid is available only on systems supporting the job control option.

kill -s kill 100 -165 - Kills job 1 of uid 165


bash-tail :
ESC+K Per tornare sui comandi precedenti
ESC+J Per tornare sui comandi successivi
ls -la :DIR
ls -1 aggio* :DIR aggio*
cd .. :andare nella cartella superiore
whatis :comando visualizza cosa fa un comando Manuale dell istruzione.
man :comando visualizza il manuale di una funzione. Premendo lo spazio si vede oltre.

ps -efa|grep sqlplus : Visualizza tutti i processi sqlplus
man kill : Visualizza l'help per l'istruzione KILL
kill -9 numprocesso (il primo numero) : COME KILLARE bene un processo
kill -9
CTRL+C : Esci -Per annullare comando
exit : Chiude
who am I : Chi sono
ls : Lista il contenuto di una directory
ls –a : Lista il contenuto di una directory compresi i files nascosti “.”
ls –l : Lista il contenuto di una directory con diversi dettagli
tail -f error_log
chmod a+x *.pl :Per dare i diritti ad un nuovo file .pl
pico nomedel file :per aprire il file in ambiente unix EDITOR

alias nome comando associa a nome il comando (per tenerlo attivo anche dopo il logout bisogna metterlo in .cshrc o .alias)
cat < file1 > file2 legge dal file1 e scrive nel file2
cat > file scrive dentro il file dall’inizio (se esiste sovrascrive)
cat >> file scrive dentro il file, ma accoda se il file esiste già
cat file permette di vedere il contenuto del file
cat file | wc –l legge il file e conta le linee (si possono esegure più comandi separandoli da |. Essi vengono eseguiti da sinistra verso destra.
cc file.c compila il file
cd .. chiude la directory
cd directory apre la directory
chgrp group file cambia il gruppo del file
chmod xxx file cambia i privilegi d’accesso del file (rwx -> proprietario, rwx -> gruppo, rwx= altri
chown user file cambia il proprietario del file
cmp file file2 compara i due file e restituisce 0 se sono uguali, 1 se sono diversi e 2 se sono illeggibili
comando & fa eseguire il comando in background
comando argomenti < file prende l’input dal file (anziché la tastiera)
comando argomenti > file redirige l’output sul file, se esiste lo sovreascrive, se non esiste lo crea
comando argomenti >> file redirige l’output sul file, se esiste accoda il testo, se non esiste lo crea
cp file path copia il file nel percorso specificato
date visualizza la data
diff file file2 visualizza le differenze tra due file
du visualizza l’occupazione del disco
env visualizza le attuali variabilidi sistema
find file cerca file
grep –c ‘testo’ file dice quante volte il testo è presente nel file
head file mostra le prime dieci linee del file
kill id termina l’applicazione con l’id inserito
ln file path crea un link del file nel percorso specificato
lpr printer file stampa il file nella stampante elencata
lprm annulla la stampa
lpstat –a visualizza lo stato delle stampanti
ls lista il contenuto di una directory
ls –a lista il contenuto di una directory compresi i files nascosti “.”
ls –l lista il contenuto di una directory con diversi dettagli
mkdir directory crea la directory
mv file file2 rinomina il file
mv file path sposta il file nel precorso specificato
ps lista dei task
pwd stampa il pathname della directory corrente
rm file rimuove il file
rm –r directory elimina la directory inclusi i file contenuti
rmdir directory elimina la directory
script salva i comandi che si fanno in un file typescript
set history=numero imposta il numero di comandi da tenere in memoria
set variabile=valore imposta il valore alla variabile per la shell corrente
setenv variabile=valore imposta il valore alla variabile per tutte le shell (stesso tipo)
sh apre una shell
sleep valore riposa per il numero di secondi immesso
sort file ordina il contenuto del file in ordine alfabetico
teil file mostra le ultime dieci linee del file
time visualizza l’ora
touch file modifica data, ora, …del file, se non esiste lo crea
unalias nome rimuove l’alias
unset variabile cancella la variabile dalla shell corrente
unsetenv variabile=valore cancella la variabile da tutte le shell (stesso tipo)
wc file conta le parole del file
who lista il nome del, terminale, data e ora d’accesso di login di tutti gli utenti collegati
who am I lista i dati d’accesso del proprio utente

Command Substitution
Next up is COMMAND SUBSTITUTION although there is a lot about quoting is this section too. It is far too difficult to split quoting away altogether, so instead I have elected to combine both sections and include all the QUOTING information here too where appropriate.
The Grave Accent (`)
We have already seen the set of back-quotes (or grave accents) in use in Script Example 1.1 and Example For Syntax where the count variable was incremented. The shell reads the command, or list of commands, or pipeline from between the grave accents and executes them. The output from this operation is then available to the shell for use in setting a variable or echoing to the terminal. When the command string is executed in this way, the output is stripped of newlines and blanks are truncated to one space between words (unless preserved in double-quotes). The grave accent example below shows several different uses of the grave accent of varying complexity.
Example grave accent
lineCount=`wc -l $fileName | cut -c1-8`
thirdPath=`echo $PATH | cut -f3-3 -d:`
lastWord=`head -$lineCount $fileName | tail -1 | tr '''/' | basename`

In order, these commands and pipelines are all used to set some variable values.

First is getting the current directory using the pwd command, the simplest usage. Just execute the command and use the output to set the variable.
Next is getting the count of lines in a file. Use the wc command (word count) with the -l flag (lines) then pipe this to the cut command and use the -c flag (characters) to cut out the 1st to 8th character (the number) from the output. Use this to set the variable. The cut is required because wc insists on including the filename in the output string. Also beware of the number part, as it is not an integer but a string of numbers. If you want a number, then use the expr command to add a zero to the result which has the effect of converting the type. Although I said earlier that shell variables are un-typed, the test command gets upset when presented with a string and is then told to evaluate it as greater or less-than another number. The variables maybe typeless, however their contents are typed unless converted.
Next is getting the third string from a complex string list. The PATH environment variable (See - Startup & Environment) is a list of search paths for the UNIX system to use when searching for command locations within the directory structure. Each path is separated from its neighbour by a colon thus: [/bin:/usr/bin:/usr/lib:/usr/etc]. This command pipeline echoes the path string into cut using the -f flag (field) to select the third field. The -d flag specifies the delimiter character for the fields as a colon in this case. Once again the result of the executed pipeline is used to set a variable.
Lastly finding the last word on a particular line. Use the head command with the line_count variable to echo out the top line_count lines of a file. Pipe this through the tail command and only pass the last one line. Having got the line you want, pipe this through tr (transform) and change each blank into a forward-slash (a UNIX directory separator). Then pipe this through basename which always strips away the full path leaving just the filename. This leaves you with just the last word, however long the line was, and however many words there were on the line, which can then be used to set our variable.
Quoting and Escaping
The difference between the single and double quote are also useful to know. The single quote is what you use to enclose a literal string. Whatever is between single quotes remains unchanged by the shell. If you enclose something in double quotes then concatenated blanks are preserved (as in the literal case with the single quotes) but variables are substituted by their values and filenames are expanded from their wild-cards to full filenames and or paths. The best way to see this is in the example below.

Example quoting
my_name="Fred Smith" # Set a variable
echo "$my_name" # Will output - Fred Smith
echo '$my_name' # Will output - $my_name

This may give the impression that the single quote is not much use. However, if you want to echo a dollar sign out to another script file for later execution, it can be very handy. See below.

echo "echo \"'$my_name'\"" > $file_name

Here the echo statement is creating another echo statement in an output file for later use. The $my_name variable is hidden inside the single-quotes and so will be passed as a literal string to the output file. Another feature shown here is the back-slash which is used as an escape signal for the shell. It tells the shell not to read the next character, but just pass it on. In this way the double-quote also makes it to the output file unscathed. The backslash can be used to escape any character that is special to the shell - even a newline. This allows you to create very long lines (See - Functions). To pass a back-slash use a double back-slash.

Parameter Substitution:
As noted earlier, the key character here is the dollar symbol ($) which instructs the shell to substitute the value where the parameter name (or variable) is located. There is a touch more flexibility here than at first appears however. There are in fact 5 different ways that the shell can substitute the value depending on the syntax used.

${name} The value, if any, is substituted. The braces are only required if name is followed by characters which are not to be interpreted as part of the name string. For instance, you might always use a temporary file name which is generated from the running script using the form "${0}.tmp" which creates a file name of "script.tmp".
${name:-word} The value, if any, is substituted. If the value is NULL, substitute word instead. Word can be a literal string, another parameter or a substituted command string output. Can be used to substitute a positional parameter ($digit).
${name:=word} As above but cannot be used to substitute a positional parameter.
${name:?word} If name is set and is not NULL, substitute its value. Else output word and exit from shell. If word is missing, the message 'parameter null or not set' is output. This can be a useful debugging aid.
${name+word} If name is set and is not NULL, substitute word. Else substitute nothing. This means the parameter is always substituted by word unless parameter is null, in which case it remains null.


PuTTY FAQ : http://www.chiark.greenend.org.uk/~sgtatham/putty/faq.html
A.1 Introduction
A.1.1 What is PuTTY?
PuTTY is a client program for the SSH, Telnet and Rlogin network protocols.

These protocols are all used to run a remote session on a computer, over a network. PuTTY implements the client end of that session: the end at which the session is displayed, rather than the end at which it runs.

In really simple terms: you run PuTTY on a Windows machine, and tell it to connect to (for example) a Unix machine. PuTTY opens a window. Then, anything you type into that window is sent straight to the Unix machine, and everything the Unix machine sends back is displayed in the window. So you can work on the Unix machine as if you were sitting at its console, while actually sitting somewhere else.

A.2 Features supported in PuTTY
In general, if you want to know if PuTTY supports a particular feature, you should look for it on the PuTTY web site. In particular:

try the changes page, and see if you can find the feature on there. If a feature is listed there, it's been implemented. If it's listed as a change made since the latest version, it should be available in the development snapshots, in which case testing will be very welcome.
try the Wishlist page, and see if you can find the feature there. If it's on there, and not in the ‘Recently fixed’ section, it probably hasn't been implemented.
A.2.1 Does PuTTY support SSH v2?
Yes. SSH v2 support has been available in PuTTY since version 0.50.

Public key authentication (both RSA and DSA) in SSH v2 is new in version 0.52.

A.2.2 Does PuTTY support reading OpenSSH or ssh.com SSHv2 private key files?
PuTTY doesn't support this natively, but as of 0.53 PuTTYgen can convert both OpenSSH and ssh.com private key files into PuTTY's format.

A.2.3 Does PuTTY support SSH v1?
Yes. SSH 1 support has always been available in PuTTY.

A.2.4 Does PuTTY support local echo?
Yes. Version 0.52 has proper support for local echo.

In version 0.51 and before, local echo could not be separated from local line editing (where you type a line of text locally, and it is not sent to the server until you press Return, so you have the chance to edit it and correct mistakes before the server sees it). New in version 0.52, local echo and local line editing are separate options, and by default PuTTY will try to determine automatically whether to enable them or not, based on which protocol you have selected and also based on hints from the server. If you have a problem with PuTTY's default choice, you can force each option to be enabled or disabled as you choose. The controls are in the Terminal panel, in the section marked ‘Line discipline options’.

A.2.5 Does PuTTY support storing settings, so I don't have to change them every time?
Yes, all of PuTTY's settings can be saved in named session profiles. See section 4.1.2 in the documentation for how to do this.

A.2.6 Does PuTTY support storing its settings in a disk file?
Not at present, although section 4.21 in the documentation gives a method of achieving the same effect.

A.2.7 Does PuTTY support full-screen mode, like a DOS box?
Yes; this is a new feature in version 0.52.

A.2.8 Does PuTTY have the ability to remember my password so I don't have to type it every time?
No, it doesn't.

Remembering your password is a bad plan for obvious security reasons: anyone who gains access to your machine while you're away from your desk can find out the remembered password, and use it, abuse it or change it.

In addition, it's not even possible for PuTTY to automatically send your password in a Telnet session, because Telnet doesn't give the client software any indication of which part of the login process is the password prompt. PuTTY would have to guess, by looking for words like ‘password’ in the session data; and if your login program is written in something other than English, this won't work.

In SSH, remembering your password would be possible in theory, but there doesn't seem to be much point since SSH supports public key authentication, which is more flexible and more secure. See chapter 8 in the documentation for a full discussion of public key authentication.

A.2.9 Is there an option to turn off the annoying host key prompts?
No, there isn't. And there won't be. Even if you write it yourself and send us the patch, we won't accept it.

Those annoying host key prompts are the whole point of SSH. Without them, all the cryptographic technology SSH uses to secure your session is doing nothing more than making an attacker's job slightly harder; instead of sitting between you and the server with a packet sniffer, the attacker must actually subvert a router and start modifying the packets going back and forth. But that's not all that much harder than just sniffing; and without host key checking, it will go completely undetected by client or server.

Host key checking is your guarantee that the encryption you put on your data at the client end is the same encryption taken off the data at the server end; it's your guarantee that it hasn't been removed and replaced somewhere on the way. Host key checking makes the attacker's job astronomically hard, compared to packet sniffing, and even compared to subverting a router. Instead of applying a little intelligence and keeping an eye on Bugtraq, the attacker must now perform a brute-force attack against at least one military-strength cipher. That insignificant host key prompt really does make that much difference.

If you're having a specific problem with host key checking - perhaps you want an automated batch job to make use of PSCP or Plink, and the interactive host key prompt is hanging the batchW process - then the right way to fix it is to add the correct host key to the Registry in advance. That way, you retain the important feature of host key checking: the right key will be accepted and the wrong ones will not. Adding an option to turn host key checking off completely is the wrong solution and we will not do it.

If you have host keys available in the common known_hosts format, we have a script called kh2reg.py to convert them to a Windows .REG file, which can be installed ahead of time by double-clicking or using REGEDIT.

A.2.10 Will you write an SSH server for the PuTTY suite, to go with the client?
No. The only reason we might want to would be if we could easily re-use existing code and significantly cut down the effort. We don't believe this is the case; there just isn't enough common ground between an SSH client and server to make it worthwhile.

If someone else wants to use bits of PuTTY in the process of writing a Windows SSH server, they'd be perfectly welcome to of course, but I really can't see it being a lot less effort for us to do that than it would be for us to write a server from the ground up. We don't have time, and we don't have motivation. The code is available if anyone else wants to try it.

A.2.11 Can PSCP or PSFTP transfer files in ASCII mode?
Unfortunately not.

Until recently, this was a limitation of the file transfer protocols: the SCP and SFTP protocols had no notion of transferring a file in anything other than binary mode. (This is still true of SCP.)

The current draft protocol spec of SFTP proposes a means of implementing ASCII transfer. At some point PSCP/PSFTP may implement this proposal.

A.3 Ports to other operating systems
The eventual goal is for PuTTY to be a multi-platform program, able to run on at least Windows, Mac OS and Unix.

Porting will become easier once PuTTY has a generalised porting layer, drawing a clear line between platform-dependent and platform-independent code. The general intention was for this porting layer to evolve naturally as part of the process of doing the first port; a Unix port has now been released and the plan seems to be working so far.

A.3.1 What ports of PuTTY exist?
Currently, release versions of PuTTY tools only run on full Win32 systems and Unix. ‘Win32’ includes Windows 95, 98, and ME, and it includes Windows NT, Windows 2000 and Windows XP.

In the development code, a partial port to the Mac OS (see question A.3.6) is under way.

Currently PuTTY does not run on Windows CE (see question A.3.4), and it does not quite run on the Win32s environment under Windows 3.1 (see question A.3.5).

We do not have release-quality ports for any other systems at the present time. If anyone told you we had an EPOC port, or an iPaq port, or any other port of PuTTY, they were mistaken. We don't.

There are some third-party ports to various platforms, mentioned on the Links page of our website.

A.3.2 Is there a port to Unix?
As of 0.54, there are Unix ports of most of the traditional PuTTY tools, and also one entirely new application.

If you look at the source release, you should find a unix subdirectory containing Makefile.gtk, which should build you Unix ports of Plink, PuTTY itself, PuTTYgen, PSCP, PSFTP, and also pterm - an xterm-type program which supports the same terminal emulation as PuTTY. We do not yet have a Unix port of Pageant.

If you don't have Gtk, you should still be able to build the command-line tools.

Note that Unix PuTTY has mostly only been tested on Linux so far; portability problems such as BSD-style ptys or different header file requirements are expected.

A.3.3 What's the point of the Unix port? Unix has OpenSSH.
All sorts of little things. pterm is directly useful to anyone who prefers PuTTY's terminal emulation to xterm's, which at least some people do. Unix Plink has apparently found a niche among people who find the complexity of OpenSSL makes OpenSSH hard to install (and who don't mind Plink not having as many features). Some users want to generate a large number of SSH keys on Unix and then copy them all into PuTTY, and the Unix PuTTYgen should allow them to automate that conversion process.

There were development advantages as well; porting PuTTY to Unix was a valuable path-finding effort for other future ports, and also allowed us to use the excellent Linux tool Valgrind to help with debugging, which has already improved PuTTY's stability on all platforms.

However, if you're a Unix user and you can see no reason to switch from OpenSSH to PuTTY/Plink, then you're probably right. We don't expect our Unix port to be the right thing for everybody.

A.3.4 Will there be a port to Windows CE or PocketPC?
It's currently being worked on, but it's only in its early stages yet, and certainly isn't yet useful. PuTTY on portable devices would clearly be a useful thing, so in the long term I hope it can be brought up to release quality.

There's also a third-party port at http://pocketputty.duxy.net/.

A.3.5 Is there a port to Windows 3.1?
PuTTY is a 32-bit application from the ground up, so it won't run on Windows 3.1 as a native 16-bit program; and it would be very hard to port it to do so, because of Windows 3.1's vile memory allocation mechanisms.

However, it is possible in theory to compile the existing PuTTY source in such a way that it will run under Win32s (an extension to Windows 3.1 to let you run 32-bit programs). In order to do this you'll need the right kind of C compiler - modern versions of Visual C at least have stopped being backwards compatible to Win32s. Also, the last time we tried this it didn't work very well.

If you're interested in running PuTTY under Windows 3.1, help and testing in this area would be very welcome!

A.3.6 Will there be a port to the Mac?
There is a port to the Mac OS in progress. It's just about usable, but has an awful lot of gaps and rough edges that will need cleaning up before release (such as useful random numbers).

A separate port to Mac OS X is also underway.

A.3.7 Will there be a port to EPOC?
I hope so, but given that ports aren't really progressing very fast even on systems the developers do already know how to program for, it might be a long time before any of us get round to learning a new system and doing the port for that.

However, some of the work has been done by other people, and a beta port of PuTTY for the Nokia 9200 Communicator series is available from http://s2putty.sourceforge.net/

A.4 Embedding PuTTY in other programs
A.4.1 Is the SSH or Telnet code available as a DLL?
No, it isn't. It would take a reasonable amount of rewriting for this to be possible, and since the PuTTY project itself doesn't believe in DLLs (they make installation more error-prone) none of us has taken the time to do it.

Most of the code cleanup work would be a good thing to happen in general, so if anyone feels like helping, we wouldn't say no.

A.4.2 Is the SSH or Telnet code available as a Visual Basic component?
No, it isn't. None of the PuTTY team uses Visual Basic, and none of us has any particular need to make SSH connections from a Visual Basic application. In addition, all the preliminary work to turn it into a DLL would be necessary first; and furthermore, we don't even know how to write VB components.

If someone offers to do some of this work for us, we might consider it, but unless that happens I can't see VB integration being anywhere other than the very bottom of our priority list.

A.4.3 How can I use PuTTY to make an SSH connection from within another program?
Probably your best bet is to use Plink, the command-line connection tool. If you can start Plink as a second Windows process, and arrange for your primary process to be able to send data to the Plink process, and receive data from it, through pipes, then you should be able to make SSH connections from your program.

This is what CVS for Windows does, for example.

A.5 Details of PuTTY's operation
A.5.1 What terminal type does PuTTY use?
For most purposes, PuTTY can be considered to be an xterm terminal.

PuTTY also supports some terminal control sequences not supported by the real xterm: notably the Linux console sequences that reconfigure the colour palette, and the title bar control sequences used by DECterm (which are different from the xterm ones; PuTTY supports both).

By default, PuTTY announces its terminal type to the server as xterm. If you have a problem with this, you can reconfigure it to say something else; vt220 might help if you have trouble.

A.5.2 Where does PuTTY store its data?
On Windows, PuTTY stores most of its data (saved sessions, SSH host keys) in the Registry. The precise location is


and within that area, saved sessions are stored under Sessions while host keys are stored under SshHostKeys.

PuTTY also requires a random number seed file, to improve the unpredictability of randomly chosen data needed as part of the SSH cryptography. This is stored by default in your Windows home directory (%HOMEDRIVE%\%HOMEPATH%), or in the actual Windows directory (such as C:\WINDOWS) if the home directory doesn't exist, for example if you're using Win95. If you want to change the location of the random number seed file, you can put your chosen pathname in the Registry, at


On Unix, PuTTY stores all of this data in a directory ~/.putty.

A.6 HOWTO questions
A.6.1 How can I make PuTTY start up maximised?
Create a Windows shortcut to start PuTTY from, and set it as ‘Run Maximized’.

A.6.2 How can I create a Windows shortcut to start a particular saved session directly?
To run a PuTTY session saved under the name ‘mysession’, create a Windows shortcut that invokes PuTTY with a command line like

\path\name\to\putty.exe -load mysession

(Note: prior to 0.53, the syntax was @session. This is now deprecated and may be removed at some point.)

A.6.3 How can I start an SSH session straight from the command line?
Use the command line putty -ssh host.name. Alternatively, create a saved session that specifies the SSH protocol, and start the saved session as shown in question A.6.2.

A.6.4 How do I copy and paste between PuTTY and other Windows applications?
Copy and paste works similarly to the X Window System. You use the left mouse button to select text in the PuTTY window. The act of selection automatically copies the text to the clipboard: there is no need to press Ctrl-Ins or Ctrl-C or anything else. In fact, pressing Ctrl-C will send a Ctrl-C character to the other end of your connection (just like it does the rest of the time), which may have unpleasant effects. The only thing you need to do, to copy text to the clipboard, is to select it.

To paste the clipboard contents into a PuTTY window, by default you click the right mouse button. If you have a three-button mouse and are used to X applications, you can configure pasting to be done by the middle button instead, but this is not the default because most Windows users don't have a middle button at all.

You can also paste by pressing Shift-Ins.

A.6.5 How do I use all PuTTY's features (public keys, proxying, cipher selection, etc.) in PSCP, PSFTP and Plink?
Most major features (e.g., public keys, port forwarding) are available through command line options. See the documentation.

Not all features are accessible from the command line yet, although we'd like to fix this. In the meantime, you can use most of PuTTY's features if you create a PuTTY saved session, and then use the name of the saved session on the command line in place of a hostname. This works for PSCP, PSFTP and Plink (but don't expect port forwarding in the file transfer applications!).

A.6.6 How do I use PSCP.EXE? When I double-click it gives me a command prompt window which then closes instantly.
PSCP is a command-line application, not a GUI application. If you run it without arguments, it will simply print a help message and terminate.

To use PSCP properly, run it from a Command Prompt window. See chapter 5 in the documentation for more details.

A.6.7 How do I use PSCP to copy a file whose name has spaces in?
If PSCP is using the traditional SCP protocol, this is confusing. If you're specifying a file at the local end, you just use one set of quotes as you would normally do:

pscp "local filename with spaces" user@host:
pscp user@host:myfile "local filename with spaces"

But if the filename you're specifying is on the remote side, you have to use backslashes and two sets of quotes:

pscp user@host:"\"remote filename with spaces\"" local_filename
pscp local_filename user@host:"\"remote filename with spaces\""

Worse still, in a remote-to-local copy you have to specify the local file name explicitly, otherwise PSCP will complain that they don't match (unless you specified the -unsafe option). The following command will give an error message:

c:\>pscp user@host:"\"oo er\"" .
warning: remote host tried to write to a file called 'oo er'
when we requested a file called '"oo er"'.

Instead, you need to specify the local file name in full:

c:\>pscp user@host:"\"oo er\"" "oo er"

If PSCP is using the newer SFTP protocol, none of this is a problem, and all filenames with spaces in are specified using a single pair of quotes in the obvious way:

pscp "local file" user@host:
pscp user@host:"remote file" .

A.7 Troubleshooting
A.7.1 Why do I see ‘Incorrect MAC received on packet’?
One possible cause of this that used to be common is a bug in old SSH 2 servers distributed by ssh.com. (This is not the only possible cause; see section 10.11 in the documentation.) Version 2.3.0 and below of their SSH 2 server constructs Message Authentication Codes in the wrong way, and expects the client to construct them in the same wrong way. PuTTY constructs the MACs correctly by default, and hence these old servers will fail to work with it.

If you are using PuTTY version 0.52 or better, this should work automatically: PuTTY should detect the buggy servers from their version number announcement, and automatically start to construct its MACs in the same incorrect manner as they do, so it will be able to work with them.

If you are using PuTTY version 0.51 or below, you can enable the workaround by going to the SSH panel and ticking the box labelled ‘Imitate SSH 2 MAC bug’. It's possible that you might have to do this with 0.52 as well, if a buggy server exists that PuTTY doesn't know about.

In this context MAC stands for Message Authentication Code. It's a cryptographic term, and it has nothing at all to do with Ethernet MAC (Media Access Control) addresses.

A.7.2 Why do I see ‘Fatal: Protocol error: Expected control record’ in PSCP?
This happens because PSCP was expecting to see data from the server that was part of the PSCP protocol exchange, and instead it saw data that it couldn't make any sense of at all.

This almost always happens because the startup scripts in your account on the server machine are generating output. This is impossible for PSCP, or any other SCP client, to work around. You should never use startup files (.bashrc, .cshrc and so on) which generate output in non-interactive sessions.

This is not actually a PuTTY problem. If PSCP fails in this way, then all other SCP clients are likely to fail in exactly the same way. The problem is at the server end.

A.7.3 I clicked on a colour in the Colours panel, and the colour didn't change in my terminal.
That isn't how you're supposed to use the Colours panel.

During the course of a session, PuTTY potentially uses all the colours listed in the Colours panel. It's not a question of using only one of them and you choosing which one; PuTTY will use them all. The purpose of the Colours panel is to let you adjust the appearance of all the colours. So to change the colour of the cursor, for example, you would select ‘Cursor Colour’, press the ‘Modify’ button, and select a new colour from the dialog box that appeared. Similarly, if you want your session to appear in green, you should select ‘Default Foreground’ and press ‘Modify’. Clicking on ‘ANSI Green’ won't turn your session green; it will only allow you to adjust the shade of green used when PuTTY is instructed by the server to display green text.

A.7.4 Plink on Windows 95 says it can't find WS2_32.DLL.
Plink requires the extended Windows network library, WinSock version 2. This is installed as standard on Windows 98 and above, and on Windows NT, and even on later versions of Windows 95; but early Win95 installations don't have it.

In order to use Plink on these systems, you will need to download the WinSock 2 upgrade:


A.7.5 After trying to establish an SSH 2 connection, PuTTY says ‘Out of memory’ and dies.
If this happens just while the connection is starting up, this often indicates that for some reason the client and server have failed to establish a session encryption key. Somehow, they have performed calculations that should have given each of them the same key, but have ended up with different keys; so data encrypted by one and decrypted by the other looks like random garbage.

This causes an ‘out of memory’ error because the first encrypted data PuTTY expects to see is the length of an SSH message. Normally this will be something well under 100 bytes. If the decryption has failed, PuTTY will see a completely random length in the region of two gigabytes, and will try to allocate enough memory to store this non-existent message. This will immediately lead to it thinking it doesn't have enough memory, and panicking.

If this happens to you, it is quite likely to still be a PuTTY bug and you should report it (although it might be a bug in your SSH server instead); but it doesn't necessarily mean you've actually run out of memory.

A.7.6 When attempting a file transfer, either PSCP or PSFTP says ‘Out of memory’ and dies.
This is almost always caused by your login scripts on the server generating output. PSCP or PSFTP will receive that output when they were expecting to see the start of a file transfer protocol, and they will attempt to interpret the output as file-transfer protocol. This will usually lead to an ‘out of memory’ error for much the same reasons as given in question A.7.5.

This is a setup problem in your account on your server, not a PSCP/PSFTP bug. Your login scripts should never generate output during non-interactive sessions; secure file transfer is not the only form of remote access that will break if they do.

On Unix, a simple fix is to ensure that all the parts of your login script that might generate output are in .profile (if you use a Bourne shell derivative) or .login (if you use a C shell). Putting them in more general files such as .bashrc or .cshrc is liable to lead to problems.

A.7.7 PSFTP transfers files much slower than PSCP.
The throughput of PSFTP 0.54 should be much better than 0.53b and prior; we've added code to the SFTP backend to queue several blocks of data rather than waiting for an acknowledgement for each. (The SCP backend did not suffer from this performance issue because SCP is a much simpler protocol.)

A.7.8 When I run full-colour applications, I see areas of black space where colour ought to be.
You almost certainly need to enable the ‘Use background colour to erase screen’ setting in the Terminal panel. Note that if you do this in mid-session, in versions before 0.54, it may not take effect until you reset the terminal (see question A.7.9).

A.7.9 When I change some terminal settings, nothing happens.
Some of the terminal options (notably Auto Wrap and background-colour screen erase) actually represent the default setting, rather than the currently active setting. The server can send sequences that modify these options in mid-session, but when the terminal is reset (by server action, or by you choosing ‘Reset Terminal’ from the System menu) the defaults are restored.

In versions 0.53b and prior, if you change one of these options in the middle of a session, you will find that the change does not immediately take effect. It will only take effect once you reset the terminal.

In version 0.54, the behaviour has changed - changes to these settings take effect immediately.

A.7.10 My PuTTY sessions unexpectedly close after they are idle for a while.
Some types of firewall, and almost any router doing Network Address Translation (NAT, also known as IP masquerading), will forget about a connection through them if the connection does nothing for too long. This will cause the connection to be rudely cut off when contact is resumed.

You can try to combat this by telling PuTTY to send keepalives: packets of data which have no effect on the actual session, but which reassure the router or firewall that the network connection is still active and worth remembering about.

Keepalives don't solve everything, unfortunately; although they cause greater robustness against this sort of router, they can also cause a loss of robustness against network dropouts. See section 4.13.5 in the documentation for more discussion of this.

A.7.11 PuTTY's network connections time out too quickly when network connectivity is temporarily lost.
This is a Windows problem, not a PuTTY problem. The timeout value can't be set on per application or per session basis. To increase the TCP timeout globally, you need to tinker with the Registry.

On Windows 95, 98 or ME, the registry key you need to create or change is


(it must be of type DWORD in Win95, or String in Win98/ME). (See MS Knowledge Base article 158474 for more information.)

On Windows NT or 2000, the registry key is


and it must be of type DWORD. (See MS Knowledge Base article 120642 for more information.)

Set the key's value to something like 10. This will cause Windows to try harder to keep connections alive instead of abandoning them.

A.7.12 When I cat a binary file, I get `PuTTYPuTTYPuTTY' on my command line.
Don't do that, then.

This is designed behaviour; when PuTTY receives the character Control-E from the remote server, it interprets it as a request to identify itself, and so it sends back the string ‘PuTTY’ as if that string had been entered at the keyboard. Control-E should only be sent by programs that are prepared to deal with the response. Writing a binary file to your terminal is likely to output many Control-E characters, and cause this behaviour. Don't do it. It's a bad plan.

To mitigate the effects, you could configure the answerback string to be empty (see section 4.3.6); but writing binary files to your terminal is likely to cause various other unpleasant behaviour, so this is only a small remedy.

A.7.13 When I cat a binary file, my window title changes to a nonsense string.
Don't do that, then.

It is designed behaviour that PuTTY should have the ability to adjust the window title on instructions from the server. Normally the control sequence that does this should only be sent deliberately, by programs that know what they are doing and intend to put meaningful text in the window title. Writing a binary file to your terminal runs the risk of sending the same control sequence by accident, and cause unexpected changes in the window title. Don't do it.

A.7.14 My keyboard stops working once PuTTY displays the password prompt.
No, it doesn't. PuTTY just doesn't display the password you type, so that someone looking at your screen can't see what it is.

Unlike the Windows login prompts, PuTTY doesn't display the password as a row of asterisks either. This is so that someone looking at your screen can't even tell how long your password is, which might be valuable information.

A.7.15 One or more function keys don't do what I expected in a server-side application.
If you've already tried all the relevant options in the PuTTY Keyboard panel, you may need to mail the PuTTY maintainers and ask.

It is not usually helpful just to tell us which application, which server operating system, and which key isn't working; in order to replicate the problem we would need to have a copy of every operating system, and every application, that anyone has ever complained about.

PuTTY responds to function key presses by sending a sequence of control characters to the server. If a function key isn't doing what you expect, it's likely that the character sequence your application is expecting to receive is not the same as the one PuTTY is sending. Therefore what we really need to know is what sequence the application is expecting.

The simplest way to investigate this is to find some other terminal environment, in which that function key does work; and then investigate what sequence the function key is sending in that situation. One reasonably easy way to do this on a Unix system is to type the command cat, and then press the function key. This is likely to produce output of the form ^[[11~. You can also do this in PuTTY, to find out what sequence the function key is producing in that. Then you can mail the PuTTY maintainers and tell us ‘I wanted the F1 key to send ^[[11~, but instead it's sending ^[OP, can this be done?’, or something similar.

You should still read the Feedback page on the PuTTY website (also provided as appendix B in the manual), and follow the guidelines contained in that.

A.7.16 Since my SSH server was upgraded to OpenSSH 3.1p1/3.4p1, I can no longer connect with PuTTY.
There is a known problem when OpenSSH has been built against an incorrect version of OpenSSL; the quick workaround is to configure PuTTY to use SSH protocol 2 and the Blowfish cipher.

For more details and OpenSSH patches, see bug 138 in the OpenSSH BTS.

This is not a PuTTY-specific problem; if you try to connect with another client you'll likely have similar problems. (Although PuTTY's default cipher differs from many other clients.)

OpenSSH 3.1p1: configurations known to be broken (and symptoms):

SSH 2 with AES cipher (PuTTY says "Assertion failed! Expression: (len & 15) == 0" in sshaes.c, or "Out of memory", or crashes)
SSH 2 with 3DES (PuTTY says "Incorrect MAC received on packet")
SSH 1 with Blowfish (PuTTY says "Incorrect CRC received on packet")
SSH 1 with 3DES
OpenSSH 3.4p1: as of 3.4p1, only the problem with SSH 1 and Blowfish remains. Rebuild your server, apply the patch linked to from bug 138 above, or use another cipher (e.g., 3DES) instead.

Other versions: we occasionally get reports of the same symptom and workarounds with older versions of OpenSSH, although it's not clear the underlying cause is the same.

A.7.17 Why do I see "Couldn't load private key from ..."? Why can PuTTYgen load my key but not PuTTY?
It's likely that you've generated an SSH protocol 2 key with PuTTYgen, but you're trying to use it in an SSH 1 connection. SSH1 and SSH2 keys have different formats, and (at least in 0.52) PuTTY's reporting of a key in the wrong format isn't optimal.

To connect using SSH 2 to a server that supports both versions, you need to change the configuration from the default (see question A.2.1).

A.7.18 When I'm connected to a Red Hat Linux 8.0 system, some characters don't display properly.
A common complaint is that hyphens in man pages show up as a-acute.

With release 8.0, Red Hat appear to have made UTF-8 the default character set. There appears to be no way for terminal emulators such as PuTTY to know this (as far as we know, the appropriate escape sequence to switch into UTF-8 mode isn't sent).

A fix is to configure sessions to RH8 systems to use UTF-8 translation - see section 4.10.1 in the documentation. (Note that if you use ‘Change Settings’, changes may not take place immediately - see question A.7.9.)

If you really want to change the character set used by the server, the right place is /etc/sysconfig/i18n, but this shouldn't be necessary.

A.7.19 Since I upgraded to PuTTY 0.54, the scrollback has stopped working when I run screen.
PuTTY's terminal emulator has always had the policy that when the ‘alternate screen’ is in use, nothing is added to the scrollback. This is because the usual sorts of programs which use the alternate screen are things like text editors, which tend to scroll back and forth in the same document a lot; so (a) they would fill up the scrollback with a large amount of unhelpfully disordered text, and (b) they contain their own method for the user to scroll back to the bit they were interested in. We have generally found this policy to do the Right Thing in almost all situations.

Unfortunately, screen is one exception: it uses the alternate screen, but it's still usually helpful to have PuTTY's scrollback continue working. The simplest solution is to go to the Features control panel and tick ‘Disable switching to alternate terminal screen’. (See section 4.6.4 for more details.)

The reason why this only started to be a problem in 0.54 is because screen typically uses an unusual control sequence to switch to the alternate screen, and previous versions of PuTTY did not support this sequence.

A.7.20 Since I upgraded Windows XP to Service Pack 2, I can't use addresses like
Some people who ask PuTTY to listen on localhost addresses other than to forward services such as SMB and Windows Terminal Services have found that doing so no longer works since they upgraded to WinXP SP2.

This is apparently an issue with SP2 that is acknowledged by Microsoft in MS Knowledge Base article 884020. The article links to a fix you can download.

(However, we've been told that SP2 also fixes the bug that means you need to use non- addresses to forward Terminal Services in the first place.)

A.7.21 PSFTP commands seem to be missing a directory separator (slash).
Some people have reported the following incorrect behaviour with PSFTP:

psftp> pwd
Remote directory is /dir1/dir2
psftp> get filename.ext
/dir1/dir2filename.ext: no such file or directory

This is not a bug in PSFTP. There is a known bug in some versions of portable OpenSSH (bug 697) that causes these symptoms; it appears to have been introduced around 3.7.x. It manifests only on certain platforms (AIX is what has been reported to us).

There is a patch for OpenSSH attached to that bug; it's also fixed in recent versions of portable OpenSSH (from around 3.8).

A.8 Security questions
A.8.1 Is it safe for me to download PuTTY and use it on a public PC?
It depends on whether you trust that PC. If you don't trust the public PC, don't use PuTTY on it, and don't use any other software you plan to type passwords into either. It might be watching your keystrokes, or it might tamper with the PuTTY binary you download. There is no program safe enough that you can run it on an actively malicious PC and get away with typing passwords into it.

If you do trust the PC, then it's probably OK to use PuTTY on it (but if you don't trust the network, then the PuTTY download might be tampered with, so it would be better to carry PuTTY with you on a floppy).

A.8.2 What does PuTTY leave on a system? How can I clean up after it?
PuTTY will leave some Registry entries, and a random seed file, on the PC (see question A.5.2). If you are using PuTTY on a public PC, or somebody else's PC, you might want to clean these up when you leave. You can do that automatically, by running the command putty -cleanup.

A.8.3 How come PuTTY now supports DSA, when the website used to say how insecure it was?
DSA has a major weakness if badly implemented: it relies on a random number generator to far too great an extent. If the random number generator produces a number an attacker can predict, the DSA private key is exposed - meaning that the attacker can log in as you on all systems that accept that key.

The PuTTY policy changed because the developers were informed of ways to implement DSA which do not suffer nearly as badly from this weakness, and indeed which don't need to rely on random numbers at all. For this reason we now believe PuTTY's DSA implementation is probably OK. However, if you have the choice, we still recommend you use RSA instead.

A.8.4 Couldn't Pageant use VirtualLock() to stop private keys being written to disk?
Unfortunately not. The VirtualLock() function in the Windows API doesn't do a proper job: it may prevent small pieces of a process's memory from being paged to disk while the process is running, but it doesn't stop the process's memory as a whole from being swapped completely out to disk when the process is long-term inactive. And Pageant spends most of its time inactive.

A.9 Administrative questions
A.9.1 Would you like me to register you a nicer domain name?
No, thank you. Even if you can find one (most of them seem to have been registered already, by people who didn't ask whether we actually wanted it before they applied), we're happy with the PuTTY web site being exactly where it is. It's not hard to find (just type ‘putty’ into google.com and we're the first link returned), and we don't believe the administrative hassle of moving the site would be worth the benefit.

In addition, if we did want a custom domain name, we would want to run it ourselves, so we knew for certain that it would continue to point where we wanted it, and wouldn't suddenly change or do strange things. Having it registered for us by a third party who we don't even know is not the best way to achieve this.

A.9.2 Would you like free web hosting for the PuTTY web site?
We already have some, thanks.

A.9.3 Would you link to my web site from the PuTTY web site?
Only if the content of your web page is of definite direct interest to PuTTY users. If your content is unrelated, or only tangentially related, to PuTTY, then the link would simply be advertising for you.

One very nice effect of the Google ranking mechanism is that by and large, the most popular web sites get the highest rankings. This means that when an ordinary person does a search, the top item in the search is very likely to be a high-quality site or the site they actually wanted, rather than the site which paid the most money for its ranking.

The PuTTY web site is held in high esteem by Google, for precisely this reason: lots of people have linked to it simply because they like PuTTY, without us ever having to ask anyone to link to us. We feel that it would be an abuse of this esteem to use it to boost the ranking of random advertisers' web sites. If you want your web site to have a high Google ranking, we'd prefer that you achieve this the way we did - by being good enough at what you do that people will link to you simply because they like you.

In particular, we aren't interested in trading links for money (see above), and we certainly aren't interested in trading links for other links (since we have no advertising on our web site, our Google ranking is not even directly worth anything to us). If we don't want to link to you for free, then we probably won't want to link to you at all.

If you have software based on PuTTY, or specifically designed to interoperate with PuTTY, or in some other way of genuine interest to PuTTY users, then we will probably be happy to add a link to you on our Links page. And if you're running a mirror of the PuTTY web site, we're definitely interested.

A.9.4 Why don't you move PuTTY to SourceForge?
Partly, because we don't want to move the web site location (see question A.9.1).

Also, security reasons. PuTTY is a security product, and as such it is particularly important to guard the code and the web site against unauthorised modifications which might introduce subtle security flaws. Therefore, we prefer that the CVS repository, web site and FTP site remain where they are, under the direct control of system administrators we know and trust personally, rather than being run by a large organisation full of people we've never met and which is known to have had breakins in the past.

No offence to SourceForge; I think they do a wonderful job. But they're not ideal for everyone, and in particular they're not ideal for us.

A.9.5 Why can't I subscribe to the putty-bugs mailing list?
Because you're not a member of the PuTTY core development team. The putty-bugs mailing list is not a general newsgroup-like discussion forum; it's a contact address for the core developers, and an internal mailing list for us to discuss things among ourselves. If we opened it up for everybody to subscribe to, it would turn into something more like a newsgroup and we would be completely overwhelmed by the volume of traffic. It's hard enough to keep up with the list as it is.

A.9.6 If putty-bugs isn't a general-subscription mailing list, what is?
There isn't one, that we know of.

If someone else wants to set up a mailing list or other forum for PuTTY users to help each other with common problems, that would be fine with us, though the PuTTY team would almost certainly not have the time to read it. It's probably better to use the established newsgroup comp.security.ssh for this purpose.

A.9.7 How can I donate to PuTTY development?
Please, please don't feel you have to. PuTTY is completely free software, and not shareware. We think it's very important that everybody who wants to use PuTTY should be able to, whether they have any money or not; so the last thing we would want is for a PuTTY user to feel guilty because they haven't paid us any money. If you want to keep your money, please do keep it. We wouldn't dream of asking for any.

Having said all that, if you still really want to give us money, we won't argue :-) The easiest way for us to accept donations is if you send money to using PayPal (www.paypal.com). Alternatively, if you don't trust PayPal, you could donate through e-gold (www.e-gold.com): deposit your donation in account number 174769, then send us e-mail to let us know you've done so (otherwise we might not notice for months!).

Small donations (tens of dollars or tens of euros) will probably be spent on beer or curry, which helps motivate our volunteer team to continue doing this for the world. Larger donations will be spent on something that actually helps development, if we can find anything (perhaps new hardware, or a copy of Windows XP), but if we can't find anything then we'll just distribute the money among the developers. If you want to be sure your donation is going towards something worthwhile, ask us first. If you don't like these terms, feel perfectly free not to donate. We don't mind.

A.9.8 Can I have permission to put PuTTY on a cover disk / distribute it with other software / etc?
Yes. You need not bother asking us explicitly for permission. You already have permission. Redistribution of the unmodified PuTTY binary in this way is entirely permitted by our licence (see appendix C), and you are welcome to do it as much as you like.

If you are distributing PuTTY within your own organisation, or for use with your own product, then we recommend (but do not insist) that you offer your own first-line technical support, to answer questions directly relating to the interaction of PuTTY with your particular environment. If your users mail us directly, we won't be able to give them very much help about things specific to your own setup.

A.10 Miscellaneous questions
A.10.1 Is PuTTY a port of OpenSSH, or based on OpenSSH?
No, it isn't. PuTTY is almost completely composed of code written from scratch for PuTTY. The only code we share with OpenSSH is the detector for SSH1 CRC compensation attacks, written by CORE SDI S.A.

A.10.2 Where can I buy silly putty?
You're looking at the wrong web site; the only PuTTY we know about here is the name of a computer program.

If you want the kind of putty you can buy as an executive toy, the PuTTY team can personally recommend Thinking Putty, which you can buy from Crazy Aaron's Putty World, at www.puttyworld.com.

A.10.3 What does ‘PuTTY’ mean?
It's the name of a popular SSH and Telnet client. Any other meaning is in the eye of the beholder. It's been rumoured that ‘PuTTY’ is the antonym of ‘getty’, or that it's the stuff that makes your Windows useful, or that it's a kind of plutonium Teletype. We couldn't possibly comment on such allegations.

A.10.4 How do I pronounce ‘PuTTY’?
Exactly like the English word ‘putty’, which we pronounce /'p?t?/.

This is Section 3 of the sed FAQ.
Go back to Section 2, or forward to Section 4.
Go up to the index.

3.1. More detailed explanation of basic sed
Sed takes a script of editing commands and applies each command, in order, to each line of input. After all the commands have been applied to the first line of input, that line is output. A second input line is taken for processing, and the cycle repeats. Sed scripts can address a single line by line number or by matching a /RE pattern/ on the line. An exclamation mark '!' after a regex ('/RE/!') or line number will select all lines that do NOT match that address. Sed can also address a range of lines in the same manner, using a comma to separate the 2 addresses.

$d # delete the last line of the file
/[0-9]\{3\}/p # print lines with 3 consecutive digits
5!s/ham/cheese/ # except on line 5, replace 'ham' with 'cheese'
/awk/!s/aaa/bb/ # unless 'awk' is found, replace 'aaa' with 'bb'
17,/foo/d # delete all lines from line 17 up to 'foo'
Following an address or address range, sed accepts curly braces '{...}' so several commands may be applied to that line or to the lines matched by the address range. On the command line, semicolons ';' separate each instruction and must precede the closing brace.

sed '/Owner:/{s/yours/mine/g;s/your/my/g;s/you/me/g;}' file
Range addresses operate differently depending on which version of sed is used (see section 3.4, below). For further information on using sed, consult the references in section 2.3, above.

3.1.1. Regular expressions on the left side of "s///"
All versions of sed support Basic Regular Expressions (BREs). For the syntax of BREs, enter "man ed" at a Unix shell prompt. A technical description of BREs from IEEE POSIX 1003.1-2001 and the Single UNIX Specification Version 3 is available online at: http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap09.html#tag_09_03

Sed normally supports BREs plus '\n' to match a newline in the pattern space, plus '\xREx' as equivalent to '/RE/', where 'x' is any character other than a newline or another backslash.

Some versions of sed support supersets of BREs, or "extended regular expressions", which offer additional metacharacters for increased flexibility. For additional information on extended REs in GNU sed, see sections 3.7 ("GNU/POSIX extensions to regular expressions") and 6.7.3 ("Special syntax in REs"), below.

Though not required by BREs, some versions of sed support \t to represent a TAB, \r for carriage return, \xHH for direct entry of hex codes, and so forth. Other versions of sed do not.

ssed (super-sed) introduced many new features for LHS pattern matching, too many to give here. The complete list is found in section 6.7.3.H ("ssed"), below.

3.1.2. Escape characters on the right side of "s///"
The right-hand side (the replacement part) in "s/find/replace/" is almost always a string literal, with no interpolation of these metacharacters:

. ^ $ [ ] { } ( ) ? + *
Three things are interpolated: ampersand (&), backreferences, and options for special seds. An ampersand on the RHS is replaced by the entire expression matched on the LHS. There is never any reason to use grouping like this:

s/\(some-complex-regex\)/one two \1 three/
since you can do this instead:

s/some-complex-regex/one two & three/
To enter a literal ampersand on the RHS, type '\&'.

Grouping and backreferences: All versions of sed support grouping and backreferences on the LHS and backreferences only on the RHS. Grouping allows a series of characters to be collected in a set, indicating the boundaries of the set with \( and \). Then the set can be designated to be repeated a certain number of times

\(like this\)* or \(like this\)\{5,7\}.
Groups can also be nested "\(like \(this\) is here\)" and may contain any valid RE. Backreferences repeat the contents of a particular group, using a backslash and a digit (1-9) for each corresponding group. In other words, "/\(pom\)\1/" is another way of writing "/pompom/". If groups are nested, backreference numbers are counted by matching \( in strict left to right order. Thus, /..\(the \(word\)\) \("foo"\)../ is matched by the backreference \3. Backreferences can be used in the LHS, the RHS, and in normal RE addressing (see section 3.3). Thus,

/\(.\)\1\(.\)\2\(.\)\3/; # matches "bookkeeper"
/^\(.\)\(.\)\(.\)\3\2\1$/; # finds 6-letter palindromes
Seds differ in how they treat invalid backreferences where no corresponding group occurs. To insert a literal ampersand or backslash into the RHS, prefix it with a backslash: \& or \\.

ssed, sed16, and sedmod permit additional options on the RHS. They all support changing part of the replacement string to upper case (\u or \U), lower case (\l or \L), or to end case conversion (\E). Both sed16 and sedmod support awk-style word references ($1, $2, $3, ...) and $0 to insert the entire line before conversion.

echo ab ghi | sed16 "s/.*/$0 - \U$2/" # prints "ab ghi - GHI"
*Note:* This feature of sed16 and sedmod will break sed scripts which put a dollar sign and digit into the RHS. Though this is an unlikely combination, it's worth remembering if you use other people's scripts.

3.1.3. Substitution switches
Standard versions of sed support 4 main flags or switches which may be added to the end of an "s///" command. They are:

N - Replace the Nth match of the pattern on the LHS, where
N is an integer between 1 and 512. If N is omitted,
the default is to replace the first match only.
g - Global replace of all matches to the pattern.
p - Print the results to stdout, even if -n switch is used.
w file - Write the pattern space to 'file' if a replacement was
done. If the file already exists when the script is
executed, it is overwritten. During script execution,
w appends to the file for each match.
GNU sed 3.02 and ssed also offer the /I switch for doing a case-insensitive match. For example,

echo ONE TWO | gsed "s/one/unos/I" # prints "unos TWO"
GNU sed 4.x and ssed add the /M switch, to simplify working with multi-line patterns: when it is used, ^ or $ will match BOL or EOL. \` and \' remain available to match the start and end of pattern space, respectively.

ssed supports two more switches, /S and /X, when its Perl mode is used. They are described in detail in section 6.7.3.H, below.

3.1.4. Command-line switches
All versions of sed support two switches, -e and -n. Though sed usually separates multiple commands with semicolons (e.g., "H;d;"), certain commands could not accept a semicolon command separator. These include :labels, 't', and 'b'. These commands had to occur last in a script, separated by -e option switches. For example:

# The 'ta' means jump to label :a if last s/// returns true
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D' file
The -n switch turns off sed's default behavior of printing every line. With -n, lines are printed only if explicitly told to. In addition, for certain versions of sed, if an external script begins with "#n" as its first two characters, the output is suppressed (exactly as if -n had been entered on the command line). A list of which versions appears in section 6.7.2., below.

GNU sed 4.x and ssed support additional switches. -l (lowercase L), followed by a number, lets you adjust the default length of the 'l' and 'L' commands (note that these implementations of sed also support an argument to these commands, to tailor the length separately of each occurrence of the command).

-i activates in-place editing (see section 4.41.1, below). -s treats each file as a separate stream: sed by default joins all the files, so $ represents the last line of the last file; 15 means the 15th line in the joined stream; and /abc/,/def/ might match across files.

When -s is used, however all addresses refer to single files. For example, $ represents the last line of each input file; 15 means the 15th line of each input file; and /abc/,/def/ will be "reset" (in other words, sed will not execute the commands and start looking for /abc/ again) if a file ends before /def/ has been matched. Note that -i automatically activates this interpretation of addresses.

3.2. Common one-line sed scripts
A separate document of over 70 handy "one-line" sed commands is available at

Here are several common sed commands for one-line use. MS-DOS users should replace single quotes ('...') with double quotes ("...") in these examples. A specific filename usually follows the script, though the input may also come via piping or redirection.

# Double space a file
sed G file

# Triple space a file
sed 'G;G' file

# Under UNIX: convert DOS newlines (CR/LF) to Unix format
sed 's/.$//' file # assumes that all lines end with CR/LF
sed 's/^M$//' file # in bash/tcsh, press Ctrl-V then Ctrl-M

# Under DOS: convert Unix newlines (LF) to DOS format
sed 's/$//' file # method 1
sed -n p file # method 2

# Delete leading whitespace (spaces/tabs) from front of each line
# (this aligns all text flush left). '^t' represents a true tab
# character. Under bash or tcsh, press Ctrl-V then Ctrl-I.
sed 's/^[ ^t]*//' file

# Delete trailing whitespace (spaces/tabs) from end of each line
sed 's/[ ^t]*$//' file # see note on '^t', above

# Delete BOTH leading and trailing whitespace from each line
sed 's/^[ ^t]*//;s/[ ^]*$//' file # see note on '^t', above

# Substitute "foo" with "bar" on each line
sed 's/foo/bar/' file # replaces only 1st instance in a line
sed 's/foo/bar/4' file # replaces only 4th instance in a line
sed 's/foo/bar/g' file # replaces ALL instances within a line

# Substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g' file

# Delete all CONSECUTIVE blank lines from file except the first.
# This method also deletes all blank lines from top and end of file.
# (emulates "cat -s")
sed '/./,/^$/!d' file # this allows 0 blanks at top, 1 at EOF
sed '/^$/N;/\n$/D' file # this allows 1 blank at top, 0 at EOF

# Delete all leading blank lines at top of file (only).
sed '/./,$!d' file

# Delete all trailing blank lines at end of file (only).
sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' file

# If a line ends with a backslash, join the next line to it.
sed -e :a -e '/\\$/N; s/\\\n//; ta' file

# If a line begins with an equal sign, append it to the previous
# line (and replace the "=" with a single space).
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D' file
3.3. Addressing and address ranges
Sed commands may have an optional "address" or "address range" prefix. If there is no address or address range given, then the command is applied to all the lines of the input file or text stream. Three commands cannot take an address prefix:

labels, used to branch or jump within the script
the close brace, '}', which ends the '{' "command"
the '#' comment character, also technically a "command"
An address can be a line number (such as 1, 5, 37, etc.), a regular expression (written in the form /RE/ or \xREx where 'x' is any character other than '\' and RE is the regular expression), or the dollar sign ($), representing the last line of the file. An exclamation mark (!) after an address or address range will apply the command to every line EXCEPT the ones named by the address. A null regex ("//") will be replaced by the last regex which was used. Also, some seds do not support \xREx as regex delimiters.

5d # delete line 5 only
5!d # delete every line except line 5
/RE/s/LHS/RHS/g # substitute only if RE occurs on the line
/^$/b label # if the line is blank, branch to ':label'
/./!b label # ... another way to write the same command
\%.%!b label # ... yet another way to write this command
$!N # on all lines but the last, get the Next line
Note that an embedded newline can be represented in an address by the symbol \n, but this syntax is needed only if the script puts 2 or more lines into the pattern space via the N, G, or other commands. The \n symbol does not match the newline at an end-of-line because when sed reads each line into the pattern space for processing, it strips off the trailing newline, processes the line, and adds a newline back when printing the line to standard output. To match the end-of-line, use the '$' metacharacter, as follows:

/tape$/ # matches the word 'tape' at the end of a line
/tape$deck/ # matches the word 'tape$deck' with a literal '$'
/tape\ndeck/ # matches 'tape' and 'deck' with a newline between
The following sed commands usually accept only a single address. All other commands (except labels, '}', and '#') accept both single addresses and address ranges.

= print to stdout the line number of the current line
a after printing the current line, append "text" to stdout
i before printing the current line, insert "text" to stdout
q quit after the current line is matched
r file prints contents of "file" to stdout after line is matched
Note that we said "usually." If you need to apply the '=', 'a', 'i', or 'r' commands to each and every line within an address range, this behavior can be coerced by the use of braces. Thus, "1,9=" is an invalid command, but "1,9{=;}" will print each line number followed by its line for the first 9 lines (and then print the rest of the rest of the file normally).

Address ranges occur in the form

, or ,!
where the address can be a line number or a standard /regex/. can also be a dollar sign, indicating the end of file. Under GNU sed 3.02+, ssed, and sed15+, may also be a notation of the form +num, indicating the next num lines after is matched.

Address ranges are:

(1) Inclusive. The range "/From here/,/eternity/" matches all the lines containing "From here" up to and including the line containing "eternity". It will not stop on the line just prior to "eternity". (If you don't like this, see section 4.24.)

(2) Plenary. They always match full lines, not just parts of lines. In other words, a command to change or delete an address range will change or delete whole lines; it won't stop in the middle of a line.

(3) Multi-linear. Address ranges normally match 2 lines or more. The second address will never match the same line the first address did; therefore a valid address range always spans at least two lines, with these exceptions which match only one line:

if the first address matches the last line of the file
if using the syntax "/RE/,3" and /RE/ occurs only once in the file at line 3 or below
if using HHsed v1.5. See section 3.4.
(4) Minimalist. In address ranges with /regex/ as , the range "/foo/,/bar/" will stop at the first "bar" it finds, provided that "bar" occurs on a line below "foo". If the word "bar" occurs on several lines below the word "foo", the range will match all the lines from the first "foo" up to the first "bar". It will not continue hopping ahead to find more "bar"s. In other words, address ranges are not "greedy," like regular expressions.

(5) Repeating. An address range will try to match more than one block of lines in a file. However, the blocks cannot nest. In addition, a second match will not "take" the last line of the previous block. For example, given the following text,

stop start
the sed command '/start/,/stop/d' will only delete the first two lines. It will not delete all 3 lines.

(6) Relentless. If the address range finds a "start" match but doesn't find a "stop", it will match every line from "start" to the end of the file. Thus, beware of the following behaviors:

/RE1/,/RE2/ # If /RE2/ is not found, matches from /RE1/ to the
# end-of-file.

20,/RE/ # If /RE/ is not found, matches from line 20 to the
# end-of-file.

/RE/,30 # If /RE/ occurs any time after line 30, each
# occurrence will be matched in sed15+, sedmod, and
# GNU sed v3.02+. GNU sed v2.05 and 1.18 will match
# from the 2nd occurrence of /RE/ to the end-of-file.
If these behaviors seem strange, remember that they occur because sed does not look "ahead" in the file. Doing so would stop sed from being a stream editor and have adverse effects on its efficiency. If these behaviors are undesirable, they can be circumvented or corrected by the use of nested testing within braces. The following scripts work under GNU sed 3.02:

# Execute your_commands on range "/RE1/,/RE2/", but if /RE2/ is
# not found, do nothing.

# Execute your_commands on range "20,/RE/", but if /RE/ is not
# found, do nothing.
As a side note, once we've used N to "slurp" lines together to test for the ending expression, the pattern space will have gathered many lines (possibly thousands) together and concatenated them as a single expression, with the \n sequence marking line breaks. The REs within the pattern space may have to be modified (e.g., you must write '/\nStart/' instead of '/^Start/' and '/[^\n]*/' instead of '/.*/') and other standard sed commands will be unavailable or difficult to use.

# Execute your_commands on range "/RE/,30", but if /RE/ occurs
# on line 31 or later, do not match it.
1,30{/RE/,$ your_commands;}
For related suggestions on using address ranges, see sections 4.2, 4.15, and 4.19 of this FAQ. Also, note the following section.

3.4. Address ranges in GNU sed and HHsed
(1) GNU sed 3.02+, ssed, and sed15+ all support address ranges like:

which match /regex/ plus the next 5 lines (or EOF, whichever comes first).

(2) GNU sed v3.02.80 (and above) and ssed support address ranges of:

as a special case to permit matching /regex/ if it occurs on the first line. This syntax permits a range expression that matches every line from the top of the file to the first instance of /regex/, even if /regex/ is on the first line.

(3) HHsed (sed15) has an exceptional way of implementing

If /RE1/ and /RE2/ both occur on the same line, HHsed will match that single line. In other words, an address range block can consist of just one line. HHsed will then look for the next occurrence of /regex1/ to begin the block again.

Every other version of sed (including sed16) requires 2 lines to match an address range, and thus /regex1/ and /regex2/ cannot successfully match just one line. See also the comments at section 7.9.4, below.

(4) BEGIN~STEP selection: ssed and GNU sed (v2.05 and above) offer a form of addressing called "BEGIN~STEP selection". This is not a range address, which selects an inclusive block of consecutive lines from /start/ to /finish/. But I think it seems to belong here.

Given an expression of the form "M~N", where M and N are integers, GNU sed and ssed will select every Nth line, beginning at line M. (With gsed v2.05, M had to be less than N, but this restriction is no longer necessary). Both M and N may equal 0 ("0~0" selects every line). These examples illustrate the syntax:

sed '1~3d' file # delete every 3d line, starting with line 1
# deletes lines 1, 4, 7, 10, 13, 16, ...

sed '0~3d' file # deletes lines 3, 6, 9, 12, 15, 18, ...

sed -n '2~5p' file # print every 5th line, starting with line 2
# prints lines 2, 7, 12, 17, 22, 27, ...
(5) Finally, GNU sed v2.05 has a bug in range addressing (see section 7.5), which was fixed in the higher versions.

3.5. Debugging sed scripts
The following two debuggers should make it easier to understand how sed scripts operate. They can save hours of grief when trying to determine the problems with a sed script.

(1) sd (sed debugger), by Brian Hiles

This debugger runs under a Unix shell, is powerful, and is easy to use. sd has conditional breakpoints and spypoints of the pattern space and hold space, on any scope defined by regex match and/or script line number. It can be semi-automated, can save diagnostic reports, and shows potential problems with a sed script before it tries to execute it. The script is robust and requires the Unix shell utilities plus the Bourne shell or Korn shell to execute.

http://sed.sourceforge.net/grabbag/scripts/sd.ksh.txt (2003)
http://sed.sourceforge.net/grabbag/scripts/sd.sh.txt (1998)
(2) sedsed, by Aurelio Jargas

This debugger requires Python to run it, and it uses your own version of sed, whatever that may be. It displays the current input line, the pattern space, and the hold space, before and after each sed command is executed.

3.6. Notes about s2p, the sed-to-perl translator
s2p (sed to perl) is a Perl program to convert sed scripts into the Perl programming language; it is included with many versions of Perl. These problems have been found when using s2p:

(1) Doesn't recognize the semicolon properly after s/// commands.

(2) Doesn't trim trailing whitespace after s/// commands. Even lone trailing spaces, without comments, produce an error.

(3) Doesn't handle multiple commands within braces. E.g.,

will produce perl code with missing braces, and miss the second "G" command as well. In fact, any commands after the first one are missed in the perl output script, and the output perl script will also contain mismatched braces.

3.7. GNU/POSIX extensions to regular expressions
GNU sed supports "character classes" in addition to regular character sets, such as [0-9A-F]. Like regular character sets, character classes represent any single character within a set.

"Character classes are a new feature introduced in the POSIX standard. A character class is a special notation for describing lists of characters that have a specific attribute, but where the actual characters themselves can vary from country to country and/or from character set to character set. For example, the notion of what is an alphabetic character differs in the USA and in France." [quoted from the docs for GNU awk v3.1.0.]

Though character classes don't generally conserve space on the line, they help make scripts portable for international use. The equivalent character sets for U.S. users follows:

[[:alnum:]] - [A-Za-z0-9] Alphanumeric characters
[[:alpha:]] - [A-Za-z] Alphabetic characters
[[:blank:]] - [ \x09] Space or tab characters only
[[:cntrl:]] - [\x00-\x19\x7F] Control characters
[[:digit:]] - [0-9] Numeric characters
[[:graph:]] - [!-~] Printable and visible characters
[[:lower:]] - [a-z] Lower-case alphabetic characters
[[:print:]] - [ -~] Printable (non-Control) characters
[[:punct:]] - [!-/:-@[-`{-~] Punctuation characters
[[:space:]] - [ \t\v\f] All whitespace chars
[[:upper:]] - [A-Z] Upper-case alphabetic characters
[[:xdigit:]] - [0-9a-fA-F] Hexadecimal digit characters
Note that [[:graph:]] does not match the space " ", but [[:print:]] does. Some character classes may (or may not) match characters in the high ASCII range (ASCII 128-255 or 0x80-0xFF), depending on which C library was used to compile sed. For non-English languages, [[:alpha:]] and other classes may also match high ASCII characters.

This is the end of Section 3 of the sed FAQ.
Go back to Section 2, or forward to Section 4.
Go up to the index.

Emacs for Vi Programmers
Installing Linux on Sony's Vaio PCG-Z505LE Laptop
Studying in New Zealand
Utilities for Programmers
Why is programming fun?
Eric Pement's Sed FAQ
C Programming Language Links (Work in Progress)
Source Code Comprehension Tools
Structure packing with the GNU C compiler
Walt Disney World Photographs


Other Stuff On This Site
Emacs for Vi Programmers
Installing Linux on Sony's Vaio PCG-Z505LE Laptop
Studying in New Zealand (July 2001 info)
Utilities for Programmers
Why is programming fun?
Mirror of Eric Pement's Sed FAQ
C Programming Language Links (Work in Progress)
Source Code Comprehension Tools
Structure packing with the GNU C compiler
Walt Disney World Photographs


Tell me what you think!

Take a look at ThingsIndian

HANDY ONE-LINERS FOR SED (Unix stream editor) Oct. 29, 1997
compiled by Eric Pement version 4.3
Latest version of this file is always at

# double space a file
sed G

# triple space a file
sed 'G;G'

# undo double-spacing (assumes even-numbered lines are always blank)
sed 'n;d'


# number each line of a file (simple left alignment). Using a tab (see
# note on '\t' at end of file) instead of space will preserve margins.
sed = filename | sed 'N;s/\n/\t/'

# number each line of a file (number on left, right-aligned)
sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /'

# number each line of file, but only print numbers if line is not blank
sed '/./=' filename | sed '/./N; s/\n/ /'

# count lines (emulates "wc -l")
sed -n '$='


# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
sed 's/.$//'

# IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
sed 's/$//' # method 1
sed -n p # method 2

# delete leading whitespace (spaces, tabs) from front of each line
# aligns all text flush left
sed 's/^[ \t]*//' # see note on '\t' at end of file

# delete trailing whitespace (spaces, tabs) from end of each line
sed 's/[ \t]*$//' # see note on '\t' at end of file

# delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//'

# insert 5 blank spaces at beginning of each line (make page offset)
sed 's/^/ /'

# align all text flush right on a 79-column width
sed -e :a -e 's/^.\{1,78\}$/ &/;ta' # set at 78 plus 1 space

# center all text in the middle of 79-column width. In method 1,
# spaces at the beginning of the line are significant, and trailing
# spaces are appended at the end of the line. In method 2, spaces at
# the beginning of the line are discarded in centering the line, and
# no trailing spaces appear at the end of lines.
sed -e :a -e 's/^.\{1,77\}$/ & /;ta' # method 1
sed -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' # method 2

# substitute (find & replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line

# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'

# reverse order of lines (emulates "tac")
sed '1!G;h;$!d'

# reverse each character on the line (emulates "rev")
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

# join pairs of lines side-by-side (like "paste")
sed 'N;s/\n/ /'


# print first 10 lines of file (emulates behavior of "head")
sed 10q

# print first line of file (emulates "head -1")
sed q

# print last 10 lines of file (emulates "tail")
sed -e :a -e '$q;N;11,$D;ba'

# print last line of file (emulates "tail -1")
sed '$!d'

# print only lines which match regular expression (emulates "grep")
sed -n '/regexp/p' # method 1
sed '/regexp/!d' # method 2

# print only lines which do NOT match regexp (emulates "grep -v")
sed -n '/regexp/!p' # method 1, corresponds to above
sed '/regexp/d' # method 2, simpler syntax

# print 1 line of context before and after regexp, with line number
# indicating where the regexp occurred (similar to "grep -A1 -B1")
sed -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h

# grep for AAA and BBB and CCC (in any order)
sed '/AAA/!d; /BBB/!d; /CCC/!d'

# grep for AAA or BBB or CCC (emulates "egrep")
sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d

# print only lines of 65 characters or longer
sed -n '/^.\{65\}/p'

# print only lines of less than 65 characters
sed -n '/^.\{65\}/!p' # method 1, corresponds to above
sed '/^.\{65\}/d' # method 2, simpler syntax

# print section of file from regular expression to end of file
sed -n '/regexp/,$p'

# print section of file based on line numbers (lines 8-12, inclusive)
sed -n '8,12p' # method 1
sed '8,12!d' # method 2

# print line number 52
sed -n '52p' # method 1
sed '52!d' # method 2
sed '52q;d' # method 3, efficient on large files

# print section of file between two regular expressions (inclusive)
sed -n '/Iowa/,/Montana/p' # case sensitive


# print all of file EXCEPT section between 2 regular expressions
sed '/Iowa/,/Montana/d'

# delete duplicate lines from a sorted file (emulates "uniq"). First
# line in a set of duplicate lines is kept, the rest are deleted
sed '$!N; /^\(.*\)\n\1$/!P; D'

# delete ALL blank lines from a file (same as "grep '.' ")
sed '/^$/d'

# delete all CONSECUTIVE blank lines from file except the first; also
# deletes all blank lines from top and end of file (emulates "cat -s")
sed '/./,/^$/!d' # method 1, allows 0 blanks at top, 1 at EOF
sed '/^$/N;/\n$/D' # method 2, allows 1 blank at top, 0 at EOF

# delete all CONSECUTIVE blank lines from file except the first 2:
sed '/^$/N;/\n$/N;//D'

# delete all leading blank lines at top of file
sed '/./,$!d'

# delete all trailing blank lines at end of file
sed -e :a -e '/^\n*$/N;/\n$/ba'


# remove nroff overstrikes (char, backspace) from man pages
sed "s/.`echo \\\b`//g" # double quotes required for Unix environment
sed 's/.\x08//g' # hex expression for GNU sed (octal is "\010")

# get Usenet/e-mail message header
sed '/^$/q' # deletes everything after first blank line

# get Usenet/e-mail message body
sed '1,/^$/d' # deletes everything up to first blank line

# get Subject header, but remove initial "Subject: " portion
sed '/^Subject: */!d; s///;q'

# get return address header
sed '/^Reply-To:/q; /^From:/h; /./d;g;q'

# parse out the address proper. Pulls out the e-mail address by itself
# from the 1-line return address header (see preceding script)
sed 's/ *(.*)//; s/>.*//; s/.*[:<] *//'

# add a leading angle bracket and space to each line (quote a message)
sed 's/^/> /

# delete leading angle bracket & space from each line (unquote a message)
sed 's/^> //'

# remove most HTML tags (accommodates multiple-line tags)
sed -e :a -e 's/<[^<]*>/ /g;/
# extract multi-part uuencoded binaries, removing extraneous header
# info, so that only the uuencoded portion remains. Files passed to
# sed must be passed in the proper order. Version 1 can be entered
# from the command line; version 2 can be made into an executable
# Unix shell script. (Modified from a script by Rahul Dhesi.)
sed '/^end/,/^begin/d' file1 file2 ... fileX | uudecode # vers. 1
sed '/^end/,/^begin/d' $* | uudecode # vers. 2

# zip up each .TXT file individually, deleting the source file and
# setting the name of each .ZIP file to the basename of the .TXT file
# (under DOS: the "dir /b" switch returns bare filenames in all caps).
echo @echo off >zipup.bat
dir /b *.txt | sed "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat

TYPICAL USE: Sed takes one or more editing commands and applies all of
them, in sequence, to each line of input. After all the commands have
been applied to the first input line, that line is output and a second
input line is taken for processing, and the cycle repeats. The
preceding examples assume that input comes from the standard input
device (i.e, the console, normally this will be piped input). One or
more filenames can be appended to the command line if the input does
not come from stdin. Output is sent to stdout (the screen). Thus:

cat filename | sed '10q' # uses piped input
sed '10q' filename # same effect, avoids a useless "cat"
sed '10q' filename > newfile # redirects output to disk

For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult "sed &
awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly,
1997; http://www.ora.com), "UNIX Text Processing," by Dale Dougherty
and Tim O'Reilly (Hayden Books, 1987) or the tutorials by Mike Arst
distributed in U-SEDIT2.ZIP (many sites). To fully exploit the power
of sed, one must understand "regular expressions." For this, see
"Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997).
The manual ("man") pages on Unix systems may be helpful (try "man
sed", "man regexp", or the subsection on regular expressions in "man
ed"), but man pages are notoriously difficult. They are not written to
teach sed use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.

QUOTING SYNTAX: The preceding examples use single quotes ('...')
instead of double quotes ("...") to enclose editing commands, since
sed is typically used on a Unix platform. Single quotes prevent the
Unix shell from intrepreting the dollar sign ($) and backquotes
(`...`), which are expanded by the shell if they are enclosed in
double quotes. Users of the "csh" shell and derivatives will also need
to quote the exclamation mark (!) with the backslash (i.e., \!) to
properly run the examples listed above, even within single quotes.
Versions of sed written for DOS invariably require double quotes
("...") instead of single quotes to enclose editing commands.

USE OF '\t' IN SED SCRIPTS: For clarity in documentation, we have used
the expression '\t' to indicate a tab character (0x09) in the scripts.
However, most versions of sed do not recognize the '\t' abbreviation,
so when typing these scripts from the command line, you should press
the TAB key instead. '\t' is supported as a regular expression
metacharacter in awk, perl, and in a few implementations of sed.

VERSIONS OF SED: Versions of sed do differ, and some slight syntax
variation is to be expected. In particular, most do not support the
use of labels (:name) or branch instructions (b,t) within editing
commands, except at the end of those commands. We have used the syntax
which will be portable to most users of sed, even though the popular
GNU versions of sed allow a more succinct syntax. When the reader sees
a fairly long command such as this:

sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d

it is heartening to know that GNU sed will let you reduce it to:

sed '/AAA/b;/BBB/b;/CCC/b;d'

In addition, remember that while many versions of sed accept a command
like "/one/ s/RE1/RE2/", some do NOT allow "/one/! s/RE1/RE2/", which
contains space before the 's'. Omit the space when typing the command.

OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to
large input files or slow processors or hard disks), substitution will
be executed more quickly if the "find" expression is specified before
giving the "s/.../.../" instruction. Thus:

sed 's/foo/bar/g' filename # standard replace command
sed '/foo/ s/foo/bar/g' filename # executes more quickly
sed '/foo/ s//bar/g' filename # shorthand sed syntax

On line selection or deletion in which you only need to output lines
from the first part of the file, a "quit" command (q) in the script
will drastically reduce processing time for large files. Thus:

sed -n '45,50p' filename # print line nos. 45-50 of a file
sed -n '51q;45,50p' filename # same, but executes much faster

If you have any additional scripts to contribute or if you find errors
in this document, please send e-mail to the compiler. Indicate the
version of sed you used, the operating system it was compiled for, and
the nature of the problem. Various scripts in this file were written
or contributed by: