Continuiamo con il nostro viaggio nel mondo della Shell Linux andando ad approfondire alcuni dei comandi più utili per comprendere come utilizzare al meglio il nostro sistema.
Iniziamo con dare una definizione di comando, che si distingue in quattro categorie differenti:
- Programmi eseguibili
- Shell builtin
- Shell function
- Alias
Programmi installati nel sistema.
Comandi che sono parte integrante della Shell. Sono comandi come cd o mkdir.
Piccoli script integrati nel sistema.
Comandi definiti dall'utente a partire da altri comandi. Utili per personalizzare il sistema.
Per capire che tipo di comando abbiamo tra le mani indovinate cosa possiamo usare? Esatto, un comando! Il comando type ci fornirà infatti informazioni su altri comandi, ad esempio mostrandoci come sono definiti nel caso degli Alias o specificando dove sono posizionati nel caso delle Shell function.
Di seguito sono riportati alcuni esempi.
user@allafinedelpalo:~$ type type type is a shell builtin user@allafinedelpalo:~$ type scp scp is /usr/bin/scp user@allafinedelpalo:~$ type mkdir mkdir is /bin/mkdir user@allafinedelpalo:~$ type ll ll is aliased to 'ls -alF' user@allafinedelpalo:~$ type ls ls is aliased to 'ls --color=auto' user@allafinedelpalo:~$ type cd cd is a shell builtin
Come possiamo vedere, lo stesso comando type è una Shell builtin in quanto parte della Shell stessa. Per scp e mkdir invece, in quanto eseguibili, type ci informa su dove si trovino nel filesystem. Il comando ll e ls sono invece Alias, che definiscono un comportamento differente dello stesso comando. È interessante notare come ls sia in realtà un Alias dello stesso comando ls, ridefinito per utilizzare i colori automatici.
Se questo non ci bastasse e volessimo rintracciare anche la posizione degli eseguibili possiamo utilizzare il comando which. Come possiamo vedere negli esempi sottostanti, il comando which funziona solamente con eseguibili e non fornisce risposta per le Shell builtin.
user@allafinedelpalo:~$ which type user@allafinedelpalo:~$ which scp /usr/bin/scp user@allafinedelpalo:~$ which mkdir /bin/mkdir user@allafinedelpalo:~$ which ll user@allafinedelpalo:~$ which ls /bin/ls user@allafinedelpalo:~$ which cd
Adesso siamo in grado di sapere il tipo di un comando e sapere la sua posizione nel filesystem. Sarebbe bello sapere anche come usare nuovi comandi di cui non conosciamo la sintassi. Come dite? Ci sarà un comando per farlo? Sbagliato, ce ne sono molti.
- help
- --help
- man
- apropos
- whatis
- info
Guida per le Shell builtin.
Mostra informazioni sull'utilizzo di un eseguibile.
Manuale per un programma eseguibile.
Ricerca di manuali.
Breve descrizione di un comando.
Mostra una info page, ovvero una alternativa a man fornita da GNU.
Prima di vederli in dettaglio, spendiamo due parole su come viene illustrata la sintassi dei comandi nei manuali. Quando ci sono dei parametri opzionali, questi saranno racchiusi tra parentesi quadre. Nel caso ci fossero più parametri opzionali mutuamente esclusivi, questi saranno divisi da una barra verticale (pipe). Ad esempio, digitando help cp ci verrà mostrata la seguente istruzione cd [-L|[-P [-e]] [-@]] [dir], ovvero che i parametri -L e -P sono opzionali e mutuamente esclusivi. In particoloare -P può essere seguito da un secondo parametro opzionale -e mentre entrambi possono essere seguiti dal parametro -@. A seguire troviamo un ultimo argomento opzionale dir.
Altri esempi potete vederli di seguito, con il comando help. Notare che per il comando ls viene restituito un errore, non essendo builtin.
user@allafinedelpalo:~$ help type type: type [-afptP] name [name ...] Display information about command type. For each NAME, indicate how it would be interpreted if used as a command name. Options: -a display all locations containing an executable named NAME; includes aliases, builtins, and functions, if and only if the '-p' option is not also used -f suppress shell function lookup -P force a PATH search for each NAME, even if it is an alias, builtin, or function, and returns the name of the disk file that would be executed -p returns either the name of the disk file that would be executed, or nothing if 'type -t NAME' would not return 'file'. -t output a single word which is one of 'alias', 'keyword', 'function', 'builtin', 'file' or '', if NAME is an alias, shell reserved word, shell function, shell builtin, disk file, or not found, respectively Arguments: NAME Command name to be interpreted. Exit Status: Returns success if all of the NAMEs are found; fails if any are not found. user@allafinedelpalo:~$ help ls bash: help: no help topics match 'ls'. Try 'help help' or 'man -k ls' or 'info ls'. user@allafinedelpalo:~$ help cd cd: cd [-L|[-P [-e]] [-@]] [dir] Change the shell working directory. Change the current directory to DIR. The default DIR is the value of the HOME shell variable. The variable CDPATH defines the search path for the directory containing DIR. Alternative directory names in CDPATH are separated by a colon (:). A null directory name is the same as the current directory. If DIR begins with a slash (/), then CDPATH is not used. If the directory is not found, and the shell option 'cdable_vars' is set, the word is assumed to be a variable name. If that variable has a value, its value is used for DIR. Options: -L force symbolic links to be followed: resolve symbolic links in DIR after processing instances of '..' -P use the physical directory structure without following symbolic links: resolve symbolic links in DIR before processing instances of '..' -e if the -P option is supplied, and the current working directory cannot be determined successfully, exit with a non-zero status -@ on systems that support it, present a file with extended attributes as a directory containing the file attributes The default is to follow symbolic links, as if '-L' were specified. '..' is processed by removing the immediately previous pathname component back to a slash or the beginning of DIR. Exit Status: Returns 0 if the directory is changed, and if $PWD is set successfully when -P is used; non-zero otherwise.
L'uso del flag --help può essere invece usato con molti eseguibili e tipicamente illustra i vari parametri che possono essere passati al programma.
user@allafinedelpalo:~$ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE scale sizes by SIZE before printing them; e.g., '--block-size=M' prints sizes in units of 1,048,576 bytes; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last modification of file status information); with -l: show ctime and sort by name; otherwise: sort by ctime, newest first -C list entries by columns --color[=WHEN] colorize the output; WHEN can be 'always' (default if omitted), 'auto', or 'never'; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -ls --color -F, --classify append indicator (one of */=>@|) to entries --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and/or -s, print human readable sizes (e.g., 1K 234M 2G) --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for disk usage -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print raw entry names (don't treat e.g. control characters specially) -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X) --time=WORD with -l, show time as WORD instead of default modification time: atime or access or use (-u); ctime or status (-c); also use specified time as sort key if --sort=time (newest first) --time-style=STYLE with -l, show times using style STYLE: full-iso, long-iso, iso, locale, or +FORMAT; FORMAT is interpreted like in 'date'; if FORMAT is FORMAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FORMAT2 to recent files; if STYLE is prefixed with 'posix-', STYLE takes effect only outside the POSIX locale -t sort by modification time, newest first -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file -1 list one file per line. Avoid '\n' with -q or -b --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000). Using color to distinguish file types is disabled both by default and with --color=never. With --color=auto, ls emits color codes only when standard output is connected to a terminal. The LS_COLORS environment variable can change the settings. Use the dircolors command to set it. Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument). GNU coreutils online help: <http://www.gnu.org/software/coreutils/> Full documentation at: <http://www.gnu.org/software/coreutils/ls> or available locally via: info '(coreutils) ls invocation'
Il comando man è probabilmente il più diffuso della lista e fornisce esattamente quello che promette: un manuale completo per il comando che stiamo utilizzando. Le informazioni che ci propone sono più strutturate e complete rispetto ai comandi visti fino ad ora, dividendole in sezioni distinte. Queste tipicamente sono il nome, una sinossi in cui sono elencati i possibili formati del comando, una descrizione testuale in cui vengono approfonditi tutti i parametri utilizzabili, l'autore del programma e informazioni su copyright e su come riportare eventuali bug.
user@allafinedelpalo:~$ man ls | cat LS(1) User Commands LS(1) NAME ls - list directory contents SYNOPSIS ls [OPTION]... [FILE]... DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is speci‐ fied. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE scale sizes by SIZE before printing them; e.g., '--block-size=M' prints sizes in units of 1,048,576 bytes; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last modification of file status information); with -l: show ctime and sort by name; other‐ wise: sort by ctime, newest first -C list entries by columns --color[=WHEN] colorize the output; WHEN can be 'always' (default if omitted), 'auto', or 'never'; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -ls --color -F, --classify append indicator (one of */=>@|) to entries --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and/or -s, print human readable sizes (e.g., 1K 234M 2G) --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for disk usage -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print raw entry names (don't treat e.g. control characters specially) -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X) --time=WORD with -l, show time as WORD instead of default modification time: atime or access or use (-u); ctime or status (-c); also use specified time as sort key if --sort=time (newest first) --time-style=STYLE with -l, show times using style STYLE: full-iso, long-iso, iso, locale, or +FORMAT; FORMAT is interpreted like in 'date'; if FORMAT is FORMAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FORMAT2 to recent files; if STYLE is prefixed with 'posix-', STYLE takes effect only outside the POSIX locale -t sort by modification time, newest first -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file -1 list one file per line. Avoid '\n' with -q or -b --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000). Using color to distinguish file types is disabled both by default and with --color=never. With --color=auto, ls emits color codes only when standard output is connected to a terminal. The LS_COLORS environment variable can change the settings. Use the dircolors command to set it. Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument). AUTHOR Written by Richard M. Stallman and David MacKenzie. REPORTING BUGS GNU coreutils online help: <http://www.gnu.org/software/coreutils/> Report ls translation bugs to <http://translationproject.org/team/> COPYRIGHT Copyright © 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO Full documentation at: <http://www.gnu.org/software/coreutils/ls> or available locally via: info '(coreutils) ls invocation' GNU coreutils 8.25 February 2016 LS(1)
I manuali proposti da man possono anche essere ricercati con il comando apropos, che data una parola chiave ritorna una lista di manuali. Lo stesso comportamento è ottenibile anche usando il comando man -k.
user@allafinedelpalo:~$ apropos mkdir gvfs-mkdir (1) - Create directories mkdir (1) - make directories mkdir (2) - create a directory mkdirat (2) - create a directory
Il comando whatis ha un comportamento simile, ma ritorna invece una descrizione sintetica dei comandi trovati.
user@allafinedelpalo:~$ whatis man man (7) - macros to format man pages man (1) - an interface to the on-line reference manuals
Infine il comando info ritorna un manuale alternativo detto info page. Questo tipo di manuale, a differenza di man contiene dei link per potersi spostare all'interno della pagina o tra altre info page. Per utilizzare i link occorre posizionarsi su di essi con il cursore del terminale e premere Invio.
Comandi personalizzati
Ora che abbiamo visto come ottenere informazioni sui comandi della Shell, proviamo a personalizzarne uno. Vi capiterà sicuramente di dover usare una serie di comandi con una certa frequenza, oppure un comando molto lungo di cui continuerete a scordarvi la sintassi. Per risolvere possiamo creare un Alias, ovvero un nuovo comando da noi definito sulla base di comandi esistenti.
Supponiamo ad esempio di voler creare delle scorciatoie per spostarci indietro di un certo numero di cartelle. Normalmente dovremmo utilizzare il comando cd .. per ogni cartella che vogliamo risalire. Con i seguenti alias sarà tutto più facile:
alias ..='cd ..' alias ...='cd ../../../' alias ....='cd ../../../../' alias .....='cd ../../../../'
Adesso digitando due punti risaliremo di una cartella, con tre punti risaliremo di due cartelle, e così via.
Per rendere permanenti gli Alias possiamo inserirli in .bashrc, come avevamo già discusso nel precedente articolo in cui avevamo introdotto anche altri Alias utili: http://www.allafinedelpalo.it/personalizziamo-il-bashrc/
Alla prossima!