fbpx

Comandos Linux – Comando sh

Comando Linux sh

comando sh

Em sistemas operacionais do tipo Unix, sh é o nome do comando do shell Bourne , o intérprete de linguagem de comando padrão do Unix e muitos sistemas operacionais do tipo Unix , incluindo Linux .

Sintaxe

sh [-acefhikmnprstuvx] [ arg ] ...

Descrição e História

sh é um intérprete de linguagem de comando que executa comandos lidos a partir de uma sequência de linhas de comando , da entrada padrão ou de um arquivo especificado .

O shell Bourne foi desenvolvido em 1977 por Stephen Bourne no AT & T ‘s de Bell Labs em 1977. Foi o shell padrão do Unix Versão sistemas 7. A maioria Unix-like conter o arquivo / bin / sh que seja o shell Bourne, ou um link simbólico (ou link físico ) para um shell compatível.

O Bourne Shell foi originalmente desenvolvido como um substituto para o shell Thompson , cujo arquivo executável também foi chamado sh . Embora seja usado como intérprete de comando interativo , seu objetivo original era funcionar como uma linguagem de script .

Os recursos do Bourne Shell incluem:

  • Os scripts podem ser chamados como comandos usando o nome do arquivo .
  • O invólucro pode ser usado interativamente ou não interativamente.
  • Os comandos podem ser executados de forma síncrona ou assíncrona.
  • O shell suporta redirecionamento de entrada e saída e pipelines .
  • Um conjunto robusto de comandos internos.
  • Construções de controle de fluxo, facilidades de cotação e funções .
  • Variáveis sem tipo .
  • Escopos variáveis locais e globais .
  • Os scripts podem ser interpretados, ou seja, eles não precisam ser compilados para serem executados.
  • Substituição de comando usando volta aspas, por exemplo: comando ` .
  • “Aqui documentos”: o uso de << para incorporar um bloco de texto de entrada em um script.
  • loops ” for / do / done ” , em particular o uso de $ * para fazer um loop sobre argumentos.
  • Mecanismo de seleção ” case / in / esac “, destinado principalmente a auxiliar na análise de argumentos .
  • Suporte para variáveis ​​de ambiente usando parâmetros de palavras-chave e variáveis ​​exportáveis.
  • Fortes disposições para o controle de entradas e saídas e em suas instalações de correspondência de expressões .

O uso do Bourne Shell foi amplamente substituído pelo Bourne-Again Shell ( bash ), que suporta recursos interativos mais amigáveis, como controle de tarefas e histórico de comandos .

Comandos

Um comando simples é uma sequência de palavras que não estão em branco separadas por espaços em branco (um espaço em branco é uma guia ou um espaço). A primeira palavra especifica o nome do comando a ser executado. Exceto conforme especificado abaixo, as palavras restantes são passadas como argumentos para o comando invocado. O nome do comando é passado como argumento 0 (consulte exec ). O valor de um comando simples é seu status de saída se terminar normalmente ou 200 + se terminar de forma anormal (consulte a visão geral de sinais do sistema operacional para obter uma lista dos valores de status).

Um pipeline é uma sequência de um ou mais comandos separados por uma barra vertical (” | “). A saída padrão de cada comando, mas o último, é conectado por um tubo à entrada padrão do próximo comando. Cada comando é executado como um processo separado; o shell aguarda o último comando terminar. O valor de um pipeline é o status de saída do seu último comando.

Uma lista é uma sequência de um ou mais pipelines separados por ” ; “, ” & “, ” && ” ou ” || ” e, opcionalmente, finalizados por ” ; ” ou ” & “. ” ; ” e ” & ” têm precedência igual que é menor do que ” && ” e ” || “, ” && ” e ” || ” também têm precedência igual. Um ponto e vírgula causa execução sequencial; um e comercial faz com que o pipeline anterior seja executado sem esperar que ele termine. O símbolo ““) faz com que a lista a seguir seja executada apenas se o pipeline anterior retornar um valor zero (diferente de zero). Novas linhas podem aparecer em uma lista, em vez de ponto e vírgula, para delimitar comandos.

Um ” # ” no início de uma palavra inicia um comentário e faz com que o restante da linha seja ignorado.

Um comando é um comando simples ou um dos seguintes. O valor retornado por um comando é o do último comando simples executado no comando:

para o nome [ na palavra …] faça a lista concluídaFor loop . Cada vez que um de comando é executado, o nome está definido para a próxima palavra no para lista de palavras. Se ‘ in word …’ for omitido, então ‘ in ” $ @ “ ‘ será assumido. A execução termina quando não houver mais palavras na lista.
palavra maiúscula em [ padrão [ padrão ] …) lista ;; ] … esacUm comando case executa a lista associada ao primeiro padrão que corresponde à palavra . A forma dos padrões é a mesma usada para a geração do nome do arquivo.
if list então list [ elif list then list ] … [ else list ] filista seguinte , se for executado, e se ele retorna zero, a lista seguinte , em seguida, é executado. Caso contrário, a lista seguinte elif ( “else if”) é executado e se o seu valor for zero, a lista seguinte , em seguida, é executado. Falha na execução da lista else .
enquanto lista [ fazer lista ] feitoenquanto comando executa repetidamente a enquanto lista , e se seu valor é zero, executa a fazer lista ; caso contrário, o loop termina. O valor devolvido por um , enquanto comando é a do último comando executado no fazer lista . até pode ser usado no lugar de enquanto para negar o teste de finalização do loop.
lista )Executar lista em um subshell.
list ; }lista é executada.
nome () { lista ; }Define o nome da função do shell . Cada vez que o nome é reconhecido como um comando, a lista é executada, com os parâmetros posicionais $ 1 , $ 2 … configurados para os argumentos do comando. Após o retorno da função, os parâmetros posicionais anteriores são restaurados.

As seguintes palavras são reconhecidas apenas como a primeira palavra de um comando e quando não estão entre aspas:

  • E se
  • então
  • outro
  • elif
  • fi
  • caso
  • no
  • esac
  • para
  • enquanto
  • até
  • Faz
  • feito
  • {
  • }

Substituição de Comando

A saída padrão de um comando incluído em um par de acentos graves (  ) pode ser usada como parte ou toda uma palavra; as novas linhas à direita são removidas. Por exemplo, se o script executável echotest.sh continha o comando:

echo "O nome deste script é 'basename $ 0`."

A execução do script exibirá a saída combinada de echo e basename :

O nome desse script é echotest.sh.

Substituição de Parâmetros

O caractere $ é usado para introduzir parâmetros substituíveis. Os parâmetros posicionais podem receber valores definidos por conjunto . As variáveis ​​podem ser definidas no formato ” nome = valor [ nome = valor ] …”.

$ { parameter }Um parâmetro é uma sequência de letras, dígitos ou sublinhados (um nome), um dígito ou qualquer um dos caracteres * @ #? – $! . O valor, se houver, do parâmetro é substituído. Os colchetes são necessários apenas quando o parâmetro é seguido por uma letra, dígito ou sublinhado que não deve ser interpretado como parte de seu nome. Se o parâmetro é um dígito, é um parâmetro posicional. Se o parâmetro for * ou @ , todos os parâmetros posicionais, começando com $ 1 , serão substituídos por espaços. $ 0 é definido a partir do argumento zero quando o shell é chamado.
$ { parâmetro : – palavra }Se o parâmetro estiver definido e não estiver vazio, substitua seu valor; caso contrário, substitua a palavra .
$ { parâmetro : = palavra }Se o parâmetro não estiver definido e não estiver vazio, defina-o como word ; o valor do parâmetro é então substituído. Os parâmetros posicionais não podem ser atribuídos dessa maneira.
$ { parâmetro 😕 palavra }Se o parâmetro estiver definido e não estiver vazio, substitua seu valor; caso contrário, imprima o word e saia do shell. Se a palavra for omitida, uma mensagem padrão será impressa.
$ { parâmetro : + palavra }Se o parâmetro estiver definido e não estiver vazio, substitua word ; caso contrário, não substitua nada.

Se o : é omitido, as substituições são executados somente se o parâmetro for definido, mesmo se ela estiver vazia.

Acima, a palavra não é avaliada, a menos que seja usada como a sequência substituída. Então, por exemplo, ” echo $ {d-`pwd`}” só executará pwd se d estiver desabilitado.

Os seguintes parâmetros são definidos automaticamente pelo shell:

#O número de parâmetros posicionais, em decimal.
Opções fornecidas ao shell na chamada ou por conjunto .
?O valor retornado pelo último comando executado, em decimal.
$O número do processo desse shell.
!O número do processo do último comando em segundo plano chamado.

Os seguintes parâmetros são usados ​​pelo shell:

CDPATHO caminho de pesquisa para o comando cd .
CASAO argumento padrão ( diretório inicial ) para o comando cd .
OPTARGO valor do último argumento da opção processado pelo comando especial getopts .
OPTINDO índice da última opção processada pelo comando especial getopts .
CAMINHOO caminho de busca de comandos (consulte Execução ).
ENVIARSe essa variável estiver definida como o nome de um arquivo de mensagens , o shell informará o usuário sobre a chegada de mensagens no arquivo especificado.
MAILCHECKSe essa variável estiver configurada, ela será interpretada como um valor em segundos para aguardar entre as verificações de novos emails. O padrão é 600 (10 minutos). Se o valor for zero, o email será verificado antes de cada prompt.
MAILPATHUma lista de arquivos separados por dois pontos que são verificados quanto a novos emails. MAIL será ignorado se esta variável estiver configurada.
PS1Sequência de caracteres do prompt primário, por padrão ‘$’ .
PS2Sequência de caracteres do prompt secundário, por padrão ‘>’ .
IFSSeparadores de campos internos, normalmente espaço, tabulação e nova linha.
LANG , LC_ALLVariáveis ​​de localidade.
LC_CTYPEAfeta o mapeamento de bytes para caracteres para geração de nome de arquivo, interpretação de ‘ \ ‘ e manipulação de $ IFS .
SHACCTSe essa variável for configurada no ambiente inicial passado para o shell e apontar para um arquivo gravável pelo usuário, as estatísticas contábeis serão gravadas nela.
TEMPO ESGOTADOO shell existe ao solicitar entrada se nenhum comando for inserido por mais do que o valor especificado em segundos. Um valor zero significa que não há tempo limite e é o padrão.

Interpretação em branco

Após a substituição de parâmetro e comando, todos os resultados da substituição são verificados quanto a caracteres separadores de campo interno (aqueles encontrados em $ IFS ) e divididos em argumentos distintos, onde esses caracteres são encontrados. Argumentos nulos explícitos ( “” ou  ) são mantidos. Os argumentos nulos implícitos (aqueles resultantes de parâmetros que não têm valores) são removidos.

Geração de nome de arquivo

Following substitution, each command word is scanned for the characters “*“, “?” and “[“. If one of these characters appears then the word is regarded as a pattern. The word is replaced with alphabetically sorted file names that match the pattern. If no file name is found that matches the pattern then the word is left unchanged. The character . at the start of a file name or immediately following a “/“, and the character “/“, must be matched explicitly.

*Matches any string, including the null string.
?Matches any single character.
[]Matches any one of the characters enclosed. A pair of characters separated by – matches any character lexically between the pair.
[!]Matches any character except the enclosed ones.

Quoting

The following characters have a special meaning to the shell and cause termination of a word unless quoted:

  • ;
  • &
  • (
  • )
  • |
  • ^
  • <
  • >
  • newline
  • space
  • tab

A character may be quoted by preceding it with a “\“. “\\newline” is ignored. All characters enclosed between a pair of quote marks (), except a single quote, are quoted. Inside double quotes (“”) parameter and command substitution occurs and “\” quotes the characters \`  and $.

$*‘ is equivalent to ‘$1 $2 …’, whereas ‘$@‘ is equivalent to ‘“$1” “$2”…’.

Prompting

When used interactively, the shell prompts with the value of $PS1 before reading a command. If at any time a newline is typed and further input is needed to complete a command then the secondary prompt ($PS2) is issued.

Input and Output

Before a command is executed its input and output may be redirected using a special notation interpreted by the shell. The following may appear anywhere in a simple-command or may precede or follow a command and are not passed on to the invoked command. Substitution occurs before word or digit is used:

<wordUse file word as standard input (file descriptor 0).
>wordUse file word as standard output (file descriptor 1). If the file does not exist then it is created; otherwise it is truncated to zero length.
>>wordUse file word as standard output. If the file exists then output is appended (by seeking to the end); otherwise the file is created.
<<[]wordThe shell input is read up to a line the same as word, or end of file. The resulting document becomes the standard input. If any character of word is quoted, then no interpretation is placed upon the characters of the document; otherwise, parameter and command substitution occurs, \newline is ignored, and \ is used to quote the characters \ $ ` and the first character of word. The optional “” causes leading tabulator character to be stripped from the resulting document; word may then also be prefixed by a tabulator.
<&digitThe standard input is duplicated from file descriptor digit. Similarly for the standard output using >.
<&-The standard input is closed. Similarly for the standard output using >.

If one of the above is preceded by a digit then the file descriptor created is that specified by the digit (instead of the default 0 or 1). For example, “… 2>&1” creates file descriptor 2 to be a duplicate of file descriptor 1. If a command is followed by & then the default standard input for the command is the empty file (/dev/null), unless job control is enabled. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input output specifications.

Environment

The environment is a list of name-value pairs that is passed to an executed program in the same way as a normal argument list; see exec and environ. The shell interacts with the environment in several ways. On invocation, the shell scans the environment and creates a parameter for each name found, giving it the corresponding value. Executed commands inherit the same environment. If the user modifies the values of these parameters or creates new ones, none of these affects the environment unless the export command is used to bind the shell’s parameter to the environment. The environment seen by any executed command is thus composed of any unmodified name-value pairs originally inherited by the shell, plus any modifications or additions, all of which must be noted in export commands.

The environment for any simple-command may be augmented by prefixing it with one or more assignments to parameters. Thus these two lines are equivalent:

TERM=450 cmd args
(export TERM; TERM=450; cmd args)

Signals

The INTERRUPT and QUIT signals for an invoked command are ignored if the command is followed by & (unless job control is enabled); otherwise signals have the values inherited by the shell from its parent. See also trap.

Execution

Each time a command is executed the above substitutions are carried out. The shell then first looks if a function with the command name was defined; if so, it is chosen for execution. Otherwise, except for the ‘special commands’ listed below a new process is created and an attempt is made to execute the command via an exec.

The shell parameter $PATH defines the search path for the directory containing the command. Each alternative directory name is separated by a colon (“:“). The default path is ‘/usr/sbin:/bin:/usr/bin:‘. If the command name contains a / then the search path is not used. Otherwise, each directory in the path is searched for an executable file. If the file has execute permission but is not an a.out file, it is assumed to be a file containing shell commands. A subshell (i.e., a separate process) is spawned to read it. A parenthesized command is also executed in a subshell.

Special Commands

:No effect; the command does nothing.
. fileRead and execute commands from file and return. The search path $PATH is used to find the directory containing file.
break [n]Exit from the enclosing for or while loop, if any. If n is specified then break n levels.
continue [n]Resume the next iteration of the enclosing for or while loop. If n is specified then resume at the nth enclosing loop.
cd [arg]Change the current directory to arg. The shell parameter $HOME is the default arg. If no directory arg is found and the $CDPATH parameter contains a list of directories separated by colons, each of these directories is used as a prefix to arg in the given order, and the current directory is set to the first one that is found.

If no suitable directory been found, an interactive shell may try to fix spelling errors and propose an alternative directory name:

cd /usf/lb
cd /usr/lib? y
ok

If the answer is ‘y‘ or anything other than ‘n‘, the shell will set the current directory to the one proposed.

echo [arg …]Each arg is printed to standard output; afterwards, a newline is printed. The following escape sequences are recognized in arg:

\bPrints a backspace character.
\cCauses the command to return immediately. Any following characters are ignored, and the terminating newline is not printed.
\fPrints a formfeed character.
\nPrints a newline character.
\rPrints a carriage-return character.
\tPrints a tabulator character.
\vPrints a vertical tabulator character.
\\Prints a backslash character.
\0nnnPrints the character (byte) with octal value nnn.

If /usr/ucb precedes /usr/sbin or /usr/bin in the current setting of the $PATH variable and the first argument is -n, the terminating newline is not printed, and no escape sequences are recognized. If the $SYSV3 variable is set in the initial environment passed to the shell, the -n argument is also interpreted, but escape sequences are processed as usual.

eval [arg …]The arguments are read as input to the shell and the resulting command(s) are executed.
exec [arg …]The command specified by the arguments is executed in place of this shell without creating a new process. Input/output arguments may appear and (if no other arguments are given) cause the shell input/output to be modified.
exit [n]Causes the shell to exit with the exit status specified by n. If n is omitted then the exit status is that of the last command executed. An end of file will also exit from the shell.
export [name …]The given names are marked for automatic export to the environment of subsequently-executed commands. If no arguments are given then a list of exportable names is printed.
getopts optstring variable [arg …]Retrieves options and option-arguments from arg (or the positional parameters) similar to getoptoptstring is a list of characters (bytes); each character represents an option letter. A character followed by “:” indicates that the option has an argument. Calling getopts repeatedly causes one option to be retrieved per call. The index of the current option is stored in the variable OPTIND; it is initialized to 1 when the shell starts. The option-argument, if any, is stored in the OPTARG variable. The option character is stored in the variable. When the end of the options is reached, getopts returns with a non-zero value. A missing argument or an illegal option also causes a non-zero return value, and an error message is printed to standard error.
hash [name …]The shell maintains a hash table of the locations of external commands. If name arguments are given, each one is looked up and is inserted into the table if it is found. Otherwise, a list of the commands currently in the table is printed.
newgrp [arg …]Equivalent to “exec newgrp arg …”.
pwdPrints the name of the present working directory.
read [-rname …One line is read from the standard input; successive words of the input are assigned to the variables name in order, with leftover words to the last variable. The return code is 0 unless end-of-file is encountered. Normally, backslashes escape the following character; this is inhibited if the -r option is given.
readonly [name …]The given names are marked readonly and the values of the these names may not be changed by subsequent assignment. If no arguments are given then a list of all readonly names is printed.
return [n]Return from a shell function to the execution level above. With the argument n, the special variable $? is set to the given value.
set [–aefhknptuvx [arg …]]
No effect; useful if the first arg begins with .
-aExport any variables that are modified or created from now on.
-eIf non-interactive, exit immediately if a command fails.
-fFile name generation is disabled.
-hWhen a function is defined, look up all external commands it contains as described for the hash special command. Normally, these commands are looked up when they are executed.
-kAll keyword arguments are placed in the environment for a command, not just those that precede the command name.
-mEnables job control (see below).
-nRead commands but do not execute them.
-pMakes the shell privileged. A privileged shell does not execute the system and user profiles; if an non-privileged shell (the default) has an effective user or group id different to its real user or group id or if it has an effective user or group id below 100, it resets its effective user or group id, respectively, to the corresponding real id at startup.
-tExit after reading and executing one command.
-uTreat unset variables as an error when substituting.
-vPrint shell input lines as they are read.
-xPrint commands and their arguments as they are executed.
Turn off the -x and -v options.

These flags can also be used upon invocation of the shell. The current set of flags may be found in $-.

If + is used instead of , the given flags are disabled.

Remaining arguments are positional parameters and are assigned, in order, to $1$2, etc. If no arguments are given then the values of all names are printed.

shift [n]The positional parameters from $2… are renamed $1… The n argument causes a shift by the given number, i.e. $n+1 is renamed to $1 and so forth.
timesImprima as horas acumuladas do usuário e do sistema para os processos executados no shell.
teste [ expr ]teste avalia a expressão expr e, se seu valor for verdadeiro, ele retornará o status de saída zero; caso contrário, um status de saída diferente de zero será retornado. teste retorna uma saída diferente de zero se não houver argumentos.

As seguintes primitivas são usadas para construir expr :

arquivo -rVerdadeiro se o arquivo existir e for legível.
arquivo -wVerdadeiro se o arquivo existir e for gravável.
arquivo -uVerdadeiro se o arquivo existir e o bit setuid estiver definido.
arquivo -gVerdadeiro se o arquivo existir e tiver o bit setgid definido.
arquivo -kTrue if the file exists and has the sticky bit set.
-f fileTrue if the file exists and is a regular file (or any file other than a directory if /usr/ucb occurs early in the current $PATH parameter).
-d fileTrue if the file exists and is a directory.
-h fileTrue if the file exists and is a symbolic link.
-L fileTrue if the file exists and is a symbolic link.
-p fileTrue if the file exists and is a named pipe.
-b fileTrue if the file exists and is a block device.
-c fileTrue if the file exists and is a character device.
-s fileTrue if the file exists and has a size greater than zero.
-t [fildes]True if the open file whose file descriptor number is fildes (1 by default) is associated with a terminal device.
-z s1True if the length of string s1 is zero.
-n s1True if the length of the string s1 is nonzero.
s1 = s2True if the strings s1 and s2 are equal.
s1 != s2True if the strings s1 and s2 are not equal.
s1True if s1 is not the null string.
n1 -eq n2Verdadeiro se os números inteiros n1 e n2 forem algebricamente iguais. Qualquer das comparações -ne , -gt , -ge , -LT , ou -le pode ser usado em lugar de eq .

Essas primárias podem ser combinadas com os seguintes operadores:

!Operador de negação unário.
-umaOperador binário AND.
-oOperador OR binário.
expr )Parênteses para agrupamento.

-a tem precedência mais alta que -o . Observe que todos os operadores e sinalizadores são argumentos separados para testar . Observe também que os parênteses são significativos como separadores de comando e devem ser escapados .

armadilha [ arg ] [ nome ] …arg é um comando a ser lido e executado quando o shell recebe sinal (es) n . Observe que arg é varrido uma vez quando a armadilha é definida e uma vez quando a armadilha é feita. Os comandos trap são executados na ordem do número do sinal. Se arg estiver ausente, todas as armadilhas n serão redefinidas para seus valores originais. Se arg for a cadeia nula, esse sinal será ignorado pelo shell e pelos comandos invocados. Se n for 0 , o comando arg será executado na saída do shell, caso contrário, após o recebimento do sinal nconforme numerado no sinal. Trap sem argumentos imprime uma lista de comandos associados a cada número de sinal. Um nome simbólico pode ser usado em vez do argumento n ; é formado pelo nome do sinal no idioma C menos o prefixo SIG , por exemplo, TERM para SIGTERM . EXIT é o mesmo que um argumento zero (‘ 0 ‘).
digite o nome …Para cada nome , imprime se seria executado como uma função shell, como um comando especial ou como um comando externo. No último caso, o nome completo do caminho para o comando também é impresso.
ulimit [  [ HS ] [ a | cdfmnstuv ]]

ulimit [  [ HS ] [ c | d | f | m | n | s | t | u | v ]] [ limite ]

Manipula limites de recursos para o shell e processos criados por ele, conforme descrito em getrlimit . Sem um argumento de limite , as configurações atuais são impressas; caso contrário, um novo limite é definido. As seguintes opções são aceitas:

-HDefine um limite rígido. Somente o superusuário pode aumentar um limite rígido.
-SDefine um limite suave. Um limite flexível não deve exceder o limite rígido.

Se nem -H ou -S for fornecido, o limite flexível será impresso ou ambos os limites serão definidos, respectivamente.

-umaEscolhe todos os limites descritos.
-cO tamanho máximo de um dump principal em blocos de 512 bytes.
-dO tamanho máximo do segmento de dados em kbytes .
-fO tamanho máximo de um arquivo em blocos de 512 bytes. Esse é o padrão se nenhum limite for selecionado explicitamente.
-euO tamanho máximo da memória bloqueada em kbytes.
-mO tamanho máximo do conjunto de residentes em kbytes.
-nO número máximo de descritores de arquivos abertos.
-sO tamanho máximo do segmento de pilha em kbytes.
-tO tempo máximo do processador em segundos.
-vocêO número máximo de processos filhos .
-vO tamanho máximo do espaço de endereço em kbytes.
umask [ -S ] [ nnn ]A máscara de criação de arquivo do usuário é configurada para o valor octal nnn (consulte umask ). Os modos simbólicos, conforme descrito no chmod, também são aceitos. Se nnn for omitido, o valor atual da máscara será impresso. Com a opção -S , a máscara atual é impressa como uma sequência simbólica.
variável não definida …Desativa cada variável nomeada.
espera [ n ]Aguarde o processo especificado e relate seu status de encerramento. Se n não for fornecido, ocorrerá uma espera para todos os processos filhos ativos no momento. O código de retorno deste comando é do processo esperado. Se n não se referir a um processo filho do shell, aguarde retorna imediatamente com o código 0 .

Invocação

Se o primeiro caractere do argumento zero for  , os comandos serão lidos em / etc / profile e $ HOME / .profile , se o arquivo respectivo existir. Os comandos são lidos como descrito abaixo. Os seguintes sinalizadores são interpretados pelo shell quando ele é chamado:

-c stringSe o sinalizador -c estiver presente, os comandos serão lidos da string .
-sSe o sinalizador -s estiver presente ou se nenhum argumento permanecer, os comandos serão lidos a partir da entrada padrão . A saída do shell é gravada no descritor de arquivo 2.
-EuSe o sinalizador -i estiver presente ou se a entrada e saída do shell estiverem conectadas a um terminal (conforme informado pela função isatty () ), esse shell será interativo. Nesse caso, o sinal de terminação SIGTERM é ignorado (para que ‘ kill 0 ‘ não mate um shell interativo) e o sinal de interrupção SIGINT seja capturado e ignorado (para que a espera seja interrompida). Em todos os casos, o SIGQUIT é ignorado pelo shell.

Os demais sinalizadores e argumentos são descritos sob o comando set .

Job Control

When an interactive shell is invoked as jsh, job control is enabled. Job control allows to stop and resume processes, and to switch between foreground and background jobs. A job consists of the commands of a single pipeline. Each job is placed in a separate process group; a login shell and all jobs created by it form a session. Interrupt, quit, and other terminal control characters only affect the current foreground process group. The foreground job can be stopped pressing the suspend key, typically ^Z; any job can be stopped by sending the STOP signal to it. Jobs are identified by job IDs of the following form:

%%%, or %+The current job.
%-The job that was previously the current job.
?stringThe only job whose name contains string.
%numberThe job with the given number.
numberThe job with process group id number.
stringThe only job for which string is a prefix of its name.

The following built-in commands are additionally available with job control:

bg [jobid …]Places each jobid in the background. The default job id is the current job.
fg [jobid …]Sequentially selects each jobid as the foreground job. The default job id is the current job.
jobs [-p|-l] [jobid …] | [-x command [arguments …]]Prints information about each jobid, or executes command:

-lIncludes the process group id and the starting directory.
-pIncludes the process group id.
-x command [arguments …]Executes command with arguments; each argument that forms a job id is replaced by the process group id of the respective job. It is an error if a given job does not exist.
kill [[-s signal | signaljobid … | -l [status]A special version of the kill command that recognizes job ids in its arguments.
stop jobid …Stops the given jobs (i.e. sends a STOP signal to them).
suspendStops the shell itself. This is not allowed if the shell is a session leader.
wait [jobid]The wait command (see above) recognizes job ids in its arguments.

Notes

For historical reasons, ^ is a synonym for | as pipeline separator. Its use in new applications is therefore discouraged.

If a command other than a simple-command (i.e. ‘for …’, ‘case …’, etc.) is redirected, it is executed in a subshell. If variable assignments must be visible in the parent shell after the input has been redirected, the exec special command can be used:

exec 5<&0 <input
while read line
do
        ...
        variable=value
        ...
done
exec <&5 5<&-

If parameters that have been inherited from the initial environment are modified, they must be explicitly exported to make the change visible to external commands, as described under ‘Environment’ above.

The $IFS parameter is applied to any unquoted word. Thus:

IFS=X
echoXfoo

executes the ‘echo‘ command with the argument ‘foo‘. The command ‘set —‘ without further arguments is a no-op (no operation). The shift special command can be used to delete all positional parameters.

There is only one namespace for both functions and parameters. A function definition will delete a parameter with the same name and vice-versa.

As atribuições de parâmetros que precedem um comando especial afetam o próprio shell; as atribuições de parâmetro que precedem a chamada de uma função são ignoradas.

arquivos

/ etc / profile
$ HOME / .profile
/ tmp / sh *
/ dev / null

Exemplos

sh

Invoca o shell Bourne e coloca você em um prompt de comando.

bc – Uma calculadora.
init – O pai de todos os processos no sistema.
kill – envia um sinal para um processo, afetando seu comportamento ou matando-o.
ksh – O interpretador de comandos do shell Korn.
login – Inicia uma sessão em um sistema.
newgrp – Entre em um novo grupo.
ps – Relate o status de um processo ou processos.
pwd – Imprime o nome do diretório de trabalho.
stty – Defina opções para o visor do seu terminal.

21 de novembro de 2019

Sobre nós

A Linux Force Brasil é uma empresa que ama a arte de ensinar. Nossa missão é criar talentos para a área de tecnologia e atender com excelência nossos clientes.

CNPJ: 13.299.207/0001-50
SAC:         0800 721 7901

[email protected]

Comercial  Comercial: (11) 3796-5900

Suporte:    (11) 3796-5900
[email protected]

Copyright © Linux Force Security  - Desde 2011.