Bourne Shell командная строка linux unix freebsd

Linux sh command

santosha.no-ip.info santosha.pro yahobby.ru

On Unix-like operating systems, sh is the command name of the Bourne shell, the standard command language interpreter of Unix and many Unix-like operating systems, including Linux.

Syntax

sh [-acefhikmnprstuvx] [<i>arg</i>] ...

Description And History

sh is a command language interpreter that executes commands read from a command line string, the standard input, or a specified file.

The Bourne shell was developed in 1977 by Stephen Bourne at AT&T‘s Bell Labs in 1977. It was the default shell of Unix Version 7. Most Unix-like systems contain the file /bin/sh that is either the Bourne shell, or a symbolic link (or hard link) to a compatible shell.

The Bourne Shell was originally developed as a replacement for the Thompson shell, whose executable file was also named sh. Although it is used as an interactive command interpreter, its original purpose was to function as a scripting language.

Features of the Bourne Shell include:

  • Scripts can be invoked as commands by using their file name.
  • The shell may be used interactively or non-interactively.
  • Commands may be executed synchronously or asynchronously.
  • The shell supports input and output redirection, and pipelines.
  • A robust set of built-in commands.
  • Flow control constructs, quotation facilities, and functions.
  • Typeless variables.
  • Both local and global variable scopes.
  • Scripts can be interpreted, i.e., they do not have to be compiled to be executed.
  • Command substitution using back quotes, e.g.: `command`.
  • “Here documents”: the use of << to embed a block of input text within a script.
  • for/do/doneloops, in particular the use of $* to loop over arguments.
  • case/in/esac” selection mechanism, primarily intended to assist argument parsing.
  • Support for environment variables using keyword parameters and exportable variables.
  • Strong provisions for controlling input and output and in its expression-matching facilities.

Use of the Bourne Shell has largely been superceded by the Bourne-Again Shell (bash), which supports more user-friendly interactive features such as job control and a command history.

Commands

A simple-command is a sequence of non-blank words separated by blanks (a blank is a tab or a space). The first word specifies the name of the command to be executed. Except as specified below, the remaining words are passed as arguments to the invoked command. The command name is passed as argument 0 (see exec). The value of a simple-command is its exit status if it terminates normally or 200+status if it terminates abnormally (see our operating system signals overview for a list of status values).

A pipeline is a sequence of one or more commands separated by a vertical bar (“|“). The standard output of each command but the last is connected by a pipe to the standard input of the next command. Each command is run as a separate process; the shell waits for the last command to terminate. The value of a pipeline is the exit status of its last command.

A list is a sequence of one or more pipelines separated by “;“, “&“, “&&” or “||” and optionally terminated by “;” or “&“. “;” and “&” have equal precedence that is lower than that of “&&” and “||“, “&&” and “||” also have equal precedence. A semicolon causes sequential execution; an ampersand causes the preceding pipeline to be executed without waiting for it to finish. The symbol “&&” (“||“) causes the list following to be executed only if the preceding pipeline returns a zero (non zero) value. Newlines may appear in a list, instead of semicolons, to delimit commands.

A “#” at the beginning of a word starts a comment and causes the rest of the line to be ignored.

A command is either a simple-command or one of the following. The value returned by a command is that of the last simple-command executed in the command:

for name [in word …] do list doneFor loop. Each time a for command is executed, name is set to the next word in the for word list. If ‘in word …’ is omitted, then ‘in “$@”‘ is assumed. Execution ends when there are no more words in the list.
case word in [pattern [| pattern ] … ) list ;;] … esacA case command executes the list associated with the first pattern that matches word. The form of the patterns is the same as that used for file name generation.
if list then list [elif list then list] … [else list] fiThe list following if is executed, and if it returns zero, the list following then is executed. Otherwise, the list following elif (“else if”) is executed and if its value is zero, the list following then is executed. Failing that the else list is executed.
while list [do list] doneA while command repeatedly executes the while list, and if its value is zero, executes the do list; otherwise the loop terminates. The value returned by a while command is that of the last executed command in the do list. until may be used in place of while to negate the loop termination test.
( list )Execute list in a subshell.
{ list; }The list is executed.
name() { list; }Defines the shell function name. Each time name is recognized as a command, list is executed, with the positional parameters $1, $2… set to the arguments of the command. After the function returns, the previous positional parameters are restored.

The following words are only recognized as the first word of a command, and when not enclosed in quotes:

  • if
  • then
  • else
  • elif
  • fi
  • case
  • in
  • esac
  • for
  • while
  • until
  • do
  • done
  • {
  • }

Command Substitution

The standard output from a command enclosed in a pair of grave accents () may be used as part or all of a word; trailing newlines are removed. For example, if the executable script echotest.sh contained the command:

echo "The name of this script is `basename $0`."

Then running the script would display the combined output of echo and basename:

The name of this script is echotest.sh.

Parameter Substitution

The character $ is used to introduce substitutable parameters. Positional parameters may be assigned values by set. Variables may be set in the form “name=value [ name=value ] …”.

${parameter}A parameter is a sequence of letters, digits or underscores (a name), a digit, or any of the characters * @ # ? – $ !. The value, if any, of the parameter is substituted. The braces are required only when parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name. If parameter is a digit then it is a positional parameter. If parameter is * or @ then all the positional parameters, starting with $1, are substituted separated by spaces. $0 is set from argument zero when the shell is invoked.
${parameter:-word}If parameter is set and not empty then substitute its value; otherwise substitute word.
${parameter:=word}If parameter is not set and not empty then set it to word; the value of the parameter is then substituted. Positional parameters may not be assigned-to in this way.
${parameter😕word}If parameter is set and not empty then substitute its value; otherwise, print word and exit from the shell. If word is omitted then a standard message is printed.
${parameter:+word}If parameter is set and not empty then substitute word; otherwise substitute nothing.

If the : is omitted, the substitutions are only executed if the parameter is set, even if it is empty.

In the above, word is not evaluated unless it is to be used as the substituted string. So, for example, “echo ${d-`pwd`}” will only execute pwd if d is unset.

The following parameters are automatically set by the shell:

#The number of positional parameters, in decimal.
Options supplied to the shell on invocation or by set.
?The value returned by the last executed command, in decimal.
$The process number of this shell.
!The process number of the last background command invoked.

The following parameters are used by the shell:

CDPATHThe search path for the cd command.
HOMEThe default argument (home directory) for the cd command.
OPTARGThe value of the last option argument processed by the getopts special command.
OPTINDThe index of the last option processed by the getopts special command.
PATHThe search path for commands (see Execution).
MAILIf this variable is set to the name of a mail file then the shell informs the user of the arrival of mail in the specified file.
MAILCHECKIf this variable is set, it is interpreted as a value in seconds to wait between checks for new mail. The default is 600 (10 minutes). If the value is zero, mail is checked before each prompt.
MAILPATHA colon-separated list of files that are checked for new mail. MAIL is ignored if this variable is set.
PS1Primary prompt string, by default ‘$ ‘.
PS2Secondary prompt string, by default ‘> ‘.
IFSInternal field separators, normally space, tab, and newline.
LANG, LC_ALLLocale variables.
LC_CTYPEAffects the mapping of bytes to characters for file name generation, for the interpretation of ‘\‘, and for handling $IFS.
SHACCTIf this variable is set in the initial environment passed to the shell and points to a file writable by the user, accounting statistics are written to it.
TIMEOUTThe shell exists when prompting for input if no command is entered for more than the given value in seconds. A value of zero means no timeout and is the default.

Blank Interpretation

After parameter and command substitution, any results of substitution are scanned for internal field separator characters (those found in $IFS) and split into distinct arguments where such characters are found. Explicit null arguments (“” or ) are retained. Implicit null arguments (those resulting from parameters that have no values) are removed.

File Name Generation

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
<b>cd /usr/lib?</b> y<b>ok</b>

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:  

 

 

 

\b Prints a backspace character.
\c Causes the command to return immediately. Any following characters are ignored, and the terminating newline is not printed.
\f Prints a formfeed character.
\n Prints a newline character.
\r Prints a carriage-return character.
\t Prints a tabulator character.
\v Prints a vertical tabulator character.
\\ Prints a backslash character.
\0nnn Prints 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.

\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.
\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.
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 getopt. optstring 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 [-r] nameOne 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 .
-a Export any variables that are modified or created from now on.
-e If non-interactive, exit immediately if a command fails.
-f File name generation is disabled.
-h When 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.
-k All keyword arguments are placed in the environment for a command, not just those that precede the command name.
-m Enables job control (see below).
-n Read commands but do not execute them.
-p Makes 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.
-t Exit after reading and executing one command.
-u Treat unset variables as an error when substituting.
-v Print shell input lines as they are read.
-x Print 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.

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.
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.
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.
timesPrint the accumulated user and system times for processes run from the shell.
test [expr]test evaluates the expression expr, and if its value is true then it returns zero exit status; otherwise, a non-zero exit status is returned. test returns a non-zero exit if there are no arguments.  

 

 

 

The following primitives are used to construct expr:

-r file True if the file exists and is readable.
-w file True if the file exists and is writable.
-u file True if the file exists and has the setuid bit set.
-g file True if the file exists and has the setgid bit set.
-k file True if the file exists and has the sticky bit set.
-f file True 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 file True if the file exists and is a directory.
-h file True if the file exists and is a symbolic link.
-L file True if the file exists and is a symbolic link.
-p file True if the file exists and is a named pipe.
-b file True if the file exists and is a block device.
-c file True if the file exists and is a character device.
-s file True 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 s1 True if the length of string s1 is zero.
-n s1 True if the length of the string s1 is nonzero.
s1 = s2 True if the strings s1 and s2 are equal.
s1 != s2 True if the strings s1 and s2 are not equal.
s1 True if s1 is not the null string.
n1 -eq n2 True if the integers n1 and n2 are algebraically equal. Any of the comparisons -ne, -gt, -ge, -lt, or -le may be used in place of -eq.

These primaries may be combined with the following operators:

! Unary negation operator.
-a Binary AND operator.
-o Binary OR operator.
( expr ) Parentheses for grouping.

-a has higher precedence than -o. Notice that all the operators and flags are separate arguments to test. Notice also that parentheses are meaningful as command separators and must be escaped.

-r fileTrue if the file exists and is readable.-w fileTrue if the file exists and is writable.-u fileTrue if the file exists and has the setuid bit set.-g fileTrue if the file exists and has the setgid bit set.-k fileTrue 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 n2True if the integers n1 and n2 are algebraically equal. Any of the comparisons -ne, -gt, -ge, -lt, or -le may be used in place of -eq.!Unary negation operator.-aBinary AND operator.-oBinary OR operator.( expr )Parentheses for grouping.
-r fileTrue if the file exists and is readable.
-w fileTrue if the file exists and is writable.
-u fileTrue if the file exists and has the setuid bit set.
-g fileTrue if the file exists and has the setgid bit set.
-k fileTrue 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 n2True if the integers n1 and n2 are algebraically equal. Any of the comparisons -ne, -gt, -ge, -lt, or -le may be used in place of -eq.
!Unary negation operator.
-aBinary AND operator.
-oBinary OR operator.
( expr )Parentheses for grouping.
trap [arg] [n|name] …The arg is a command to be read and executed when the shell receives signal(s) n. Note that arg is scanned once when the trap is set and once when the trap is taken. trap commands are executed in order of signal number. If arg is absent then all trap(s) n are reset to their original values. If arg is the null string then this signal is ignored by the shell and by invoked commands. If n is 0 then the command arg is executed on exit from the shell, otherwise upon receipt of signal n as numbered in signal. Trap with no arguments prints a list of commands associated with each signal number. A symbolic name can be used instead of the n argument; it is formed by the signal name in the C language minus the SIG prefix, e.g., TERM for SIGTERM. EXIT is the same as a zero (‘0‘) argument.
type nameFor each name, prints if it would be executed as a shell function, as a special command, or as an external command. In the last case, the full path name to the command is also printed.
ulimit [[HS][a|cdfmnstuv]]  

 

 

 

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

Handles resource limits for the shell and processes created by it, as described in getrlimit. Without a limit argument, the current settings are printed; otherwise, a new limit is set. The following options are accepted:  

 

 

 

-H Sets a hard limit. Only the super-user may raise a hard limit.
-S Sets a soft limit. A soft limit must not exceed the hard limit.  

 

 

 

If neither -H or -S is given, the soft limit is printed, or both limits are set, respectively.

-a Chooses all limits described.
-c The maximum size of a core dump in 512-byte blocks.
-d The maximum size of the data segment in kbytes.
-f The maximum size of a file in 512-byte blocks. This is the default if no limit is explicitly selected.
-l The maximum size of locked memory in kbytes.
-m The maximum resident set size in kbytes.
-n The maximum number of open file descriptors.
-s The maximum size of the stack segment in kbytes.
-t The maximum processor time in seconds.
-u The maximum number of child processes.
-v The maximum address space size in kbytes.
-HSets a hard limit. Only the super-user may raise a hard limit.-SSets a soft limit. A soft limit must not exceed the hard limit.  

 

 

 

If neither -H or -S is given, the soft limit is printed, or both limits are set, respectively.

-aChooses all limits described.-cThe maximum size of a core dump in 512-byte blocks.-dThe maximum size of the data segment in kbytes.-fThe maximum size of a file in 512-byte blocks. This is the default if no limit is explicitly selected.-lThe maximum size of locked memory in kbytes.-mThe maximum resident set size in kbytes.-nThe maximum number of open file descriptors.-sThe maximum size of the stack segment in kbytes.-tThe maximum processor time in seconds.-uThe maximum number of child processes.-vThe maximum address space size in kbytes.
-HSets a hard limit. Only the super-user may raise a hard limit.
-SSets a soft limit. A soft limit must not exceed the hard limit.  

 

 

 

If neither -H or -S is given, the soft limit is printed, or both limits are set, respectively.

-aChooses all limits described.
-cThe maximum size of a core dump in 512-byte blocks.
-dThe maximum size of the data segment in kbytes.
-fThe maximum size of a file in 512-byte blocks. This is the default if no limit is explicitly selected.
-lThe maximum size of locked memory in kbytes.
-mThe maximum resident set size in kbytes.
-nThe maximum number of open file descriptors.
-sThe maximum size of the stack segment in kbytes.
-tThe maximum processor time in seconds.
-uThe maximum number of child processes.
-vThe maximum address space size in kbytes.
umask [-S] [nnn]The user file creation mask is set to the octal value nnn (see umask). Symbolic modes as described in chmod are also accepted. If nnn is omitted, the current value of the mask is printed. With the -S option, the current mask is printed as a symbolic string.
unset variableUnsets each variable named.
wait [n]Wait for the specified process and report its termination status. If n is not given then a wait occurs for all currently active child processes. The return code from this command is of the waited process. If n does not refer to a child process of the shell, wait returns immediately with code 0.

Invocation

If the first character of argument zero is , commands are read from /etc/profile and $HOME/.profile, if the respective file exists. Commands are then read as described below. The following flags are interpreted by the shell when it is invoked:

-c stringIf the -c flag is present then commands are read from string.
-sIf the -s flag is present or if no arguments remain then commands are read from the standard input. Shell output is written to file descriptor 2.
-iIf the -i flag is present or if the shell input and output are attached to a terminal (as told by the function isatty()) then this shell is interactive. In this case the terminate signal SIGTERM is ignored (so that ‘kill 0‘ does not kill an interactive shell) and the interrupt signal SIGINT is caught and ignored (so that wait is interruptible). In all cases SIGQUIT is ignored by the shell.

The remaining flags and arguments are described under the set command.

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:  

 

 

 

-l Includes the process group id and the starting directory.
-p Includes 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.
-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.
-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 | signal] jobid … | -l [status]A special version of the kill command that recognizes job ids in its arguments.
stop jobidStops 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.

Parameter assignments that precede a special command affect the shell itself; parameter assignments that precede the call of a function are ignored.

Files

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

Examples

sh

Invokes the Bourne shell, and places you at a command prompt.

bc — A calculator.
init — The parent of all processes on the system.
kill — Send a signal to a process, affecting its behavior or killing it.
ksh — The Korn shell command interpreter.
login — Begin a session on a system.
newgrp — Log into a new group.
ps — Report the status of a process or processes.
pwd — Print the name of the working directory.
stty — Set options for your terminal display.

здесь будет парочка примеров example code

на русский не перевожу это сделает переводчик .. если в скрипт надо добавить что то еще это можно сделать используя системные команды  например `date` или `expr $A + $B` соответственно складываются числа или выводится время и много всего еще. Коммандная строка FreeBSD sh  а в ubuntu bash. А если это не устраивает – легко меняется.

#!/usr/bin/env bash

в первую строчку

Unix shell: абсолютно первые шаги

  • Tutorial

Зачем и для кого статья?


Изначально это была памятка для студентов, которые начинают работать с unix-подобными системами. Иными словами, статья рассчитана на тех, кто не имеет предыдущего опыта работы в unix-овой командной строке, но по тем или иным причинам хочет или должен научиться эффективно с нею взаимодействовать.

Здесь не будет пересказа манов (документации), и статья никак не отменяет и не заменяет их чтение. Вместо этого я расскажу о главных вещах (командах, приемах и принципах), которые надо осознать с самого начала работы в unix shell-е, чтобы работа происходила эффективно и приятно.

Статья касается полноценных unix-подобных окружений, с полнофункциональным шеллом (предпочтительно zsh или bash)и достаточно широким набором стандартных программ.

Что такое шелл


Shell (шелл, он же «командная строка», он же CLI, он же «консоль», он же «терминал», он же «черное окошко с белыми буковками») — это текстовый интерфейс общения с операционной системой (ну, строго говря, это программа, которая таковой интерфейс обеспечивает, но сейчас это различие несущественно).

В целом работа через шелл выглядит так: пользователь (т.е. вы) с клавиатуры вводит команду, нажимает Enter, система выполняет команду, пишет на экран результат выполнения, и снова ожидает ввода следующей команды.

Типичный вид шелла:
типичный вид шелла

Шелл — это основной способ для взаимодействия со всеми Unix-подобными серверными системами.

Где встречаются системы с командной строкой?


Где вас может поджидать unix-овый шелл, популярные варианты:
  • MacOS (bash);
  • удаленный доступ на сервер по работе или для личного веб-проекта;
  • домашний файл-сервер с удаленным доступом;
  • Ubuntu, PC-BSD на ноутбуке/десктопе — unix-подобные системы сегодня просты в установке и использовании.


Какие задачи разумно решать шеллом?


Естественные задачи, для которых шелл пригоден, полезен и незаменим:
  • интерактивная работа в терминале:
    • выполнение компиляции, запуск заданий через make;
    • сравнение текстовых файлов;
    • быстрый ad-hoc анализ данных (количество уникальных ip в логе, распределение записей по часам/минутам и т.п.);
    • разовые массовые действия (прибить много процессов; если работаете с системой контроля версий — ревертнуть или зарезолвить кучу файлов);
    • диагностика происходящего в системе (семафоры, локи, процессы, дескрипторы, место на диске и т.п.);
  • скриптование:
    • установочные скрипты, для выполнения которых нельзя рассчитывать на наличие других интерпретаторов — это не для новичков;
    • функции для кастомизации интерактивного шелла (влияющие на приглашение, меняющие каталог, устанавливающие переменные окружения) — тоже не совсем для новичков;
    • одноразовые скрипты типа массового перекодирования файлов;
    • makefile-ы.


Абсолютно первые шаги


Начинаем работу: войти и выйти


Убедитесь, что точно знаете, как запустить шелл и как из него выйти.

Если вы работаете за машиной, на которой установлена Ubuntu, вам надо запустить программу Terminal. По окончании работы можно просто закрыть окно.

На MacOS — тоже запустить Terminal.

Для доступа к удаленному серверу — воспользоваться ssh (если локально у вас MacOS, Ubuntu или другая unix-like система) или putty (если у вас Windows).

Кто я, где я?


Выполните следующие команды:
  • hostname — выводит имя машины (сервера), на которой вы сейчас находитесь;
  • whoami — выводит ваш логин (ваше имя в системе);
  • tree -d / |less — псевдографическое изображение дерева каталогов на машине; выход из пролистывания — q;
  • pwd — выводит каталог, в котором вы сейчас находитесь; в командной строке вы не можете быть «просто так», вы обязательно находитесь в каком-то каталоге (=текущий каталог, рабочий каталог). Вероятно, текущий рабочий каталог выводится у вас в приглашении (prompt).
  • ls — список файлов в текущем каталоге; ls /home — список файлов в указанном каталоге;


История команд (history)


Важное свойство полноценной командной строки — история команд.

Выполните несколько команд: hostname, ls, pwd, whoami. Теперь нажмите клавишу «вверх». В строке ввода появилась предыдущая команда. Клавишами «вверх» и «вниз» можно перемещаться вперед и назад по истории. Когда долистаете до hostname, нажмите Enter — команда выполнится еще раз.

Команды из истории можно не просто выполнять повторно, а еще и редактировать. Долистайте историю до команды ls, добавьте к ней ключ -l (получилось ls -l, перед минусом пробел есть, а после — нет). Нажмите Enter — выполнится модифицированная команда.

Пролистывание истории, редактирование и повторное выполнение команд — самые типичные действия при работе в командной строке, привыкайте.

Copy-paste


Командная строка очень текстоцентрична: команды — это текст, входные данные для большинства стандартных программ — текст, результат работы — чаще всего тоже текст.

Прекрасной особенностью текста является то, что его можно копировать и вставлять, это верно и для командной строки.

Попробуйте выполнить команду date +"%y-%m-%d, %A"
Вводили ли вы ее целиком руками или скопировали из статьи? Убедитесь, что вы можете ее скопировать, вставить в терминал и выполнить.

После того, как научитесь пользоваться man‘ом, убедитесь, что можете скопировать и выполнить примеры команд из справки. Для проверки найдите в справке по программе date раздел EXAMPLES, скопируйте и выполните первый приведенный пример (на всякий случай: знак доллара не является частью команды, это условное изображение приглашения к вводу).

Как именно копировать текст из терминала и вставлять его в терминал — зависит от вашей системы и от ее настроек, поэтому дать универсальную инструкцию, к сожалению, не получится. На Ubuntu попробуйте так: копирование — просто выделение мышью, вставка — средняя кнопка мыши. Если не работает, или если у вас другая система — поищите в Интернете или спросите более опытных знакомых.

Ключи и опции


При исследовании истории команд вы уже столкнулись с тем, что у команды ls есть по крайней мере два варианта. Если вызвать ее просто так, она выводит простой список:

[22:26]akira@latitude-e7240:
~/shell-survival-quide> ls
Makefile  shell-first-steps.md  shell-first-steps.pdf
shell-survival-quide.md  shell-survival-quide.pdf

Если же добавить ключ -l, к каждому файлу выводится подробная информация:

[22:28]akira@latitude-e7240:
~/shell-survival-quide> ls -l 
total 332
-rw-rw-r-- 1 akira akira    198 Feb 13 11:48 Makefile
-rw-rw-r-- 1 akira akira  15107 Feb 14 22:26 shell-first-steps.md
-rw-rw-r-- 1 akira akira 146226 Feb 13 11:49 shell-first-steps.pdf
-rw-rw-r-- 1 akira akira  16626 Feb 13 11:45 shell-survival-quide.md
-rw-rw-r-- 1 akira akira 146203 Feb 13 11:35 shell-survival-quide.pdf

Это очень типичная ситуация: если к вызову команды добавлять специальные модификаторы (ключи, опции, параметры), поведение команды меняется. Сравните: tree / и tree -d /, hostname и hostname -f.

Кроме того, команды могут принимать в качестве параметров имена файлов, каталогов или просто текстовые строки. Попробуйте:

ls -ld /home
ls -l /home
grep root /etc/passwd


man


man — справка по командам и программам, доступным на вашей машине, а также по системным вызовам и стандартной библиотеке C.

Попробуйте: man grep, man atoi, man chdir, man man.

Пролистывание вперед и назад делается кнопками «вверх», «вниз», «PageUp», «PageDown», выход из просмотра справки — кнопкой q. Поиск определенного текста в справочной статье: нажимите / (прямой слеш), введите текст для поиска, нажимите Enter. Перемещение к следующим вхождениям — клавиша n.

Все справочные статьи делятся на категории. Самые важные:
  • 1 — исполняемые программы и шелльные команды (wc, ls, pwd и т.п.);
  • 2 — системные вызовы (fork, dup2 и т.п.)
  • 3 — библиотечные функции (printf, scanf, cos, exec).

Указывать, из какой именно категории надо показать справку, нужно в случаях совпадений имен. Например, man 3 printf описывает функцию из стандартной библиотеки C, а man 1 printf — консольную программу с таким же именем.

Посмотреть список всех доступных на машине справочных статей можно с помощью команды man -k . (точка — тоже часть комады).

less


Когда в небольшом окне терминала надо просмотреть очень длинный текст (содержимое какого-то файла, длинный man и т.п.), используют специальные программы-«пейджеры» (от слова page/страница, то есть постраничные листатели). Самый популярный листатель — less, и именно он обеспечивает вам пролистывание, когда вы читаете man-ы.

Попробуйте и сравните поведение:

cat /etc/bash.bashrc 
cat /etc/bash.bashrc |less 


Можно передать файл в пролистыватель сразу в параметрах:

less /etc/bash.bashrc 


Пролистывание вверхи и вниз — кнопки «вверх», «вниз», «PageUp», «PageDown», выход — кнопка q. Поиск определенного текста: нажимите / (прямой слеш), введите текст для поиска, нажимите Enter. Перемещение к следующим вхождениям — клавиша n. (Узнаете инструкцию про man? Ничего удивительного, для вывода справки тоже используется less.)

Права


С любым файлом или каталогом связан набор «прав»: право на чтение файла, право на запись в файл, право исполнять файл. Все пользователи делятся на три категории: владелец файла, группа владельца файла, все прочие пользователи.

Посмотреть права на файл можно с помощью ls -l. Например:

> ls -l Makefile
-rw-r--r-- 1 akira students    198 Feb 13 11:48 Makefile

Этот вывод означает, что владельцу (akira) можно читать и писать файл, группе (students) — только читать, всем прочим пользователя — тоже только читать.

Если при работе вы получаете сообщение permission denied, это значит, что у вас недостаточно правна объект, с которым вы хотели работать.

Подробнее читайте в man chmod.

STDIN, STDOUT, конвейеры (пайпы)


С каждой исполняющейся программой связаны 3 стандартных потока данных: поток входных данных STDIN, поток выходных данных STDOUT, поток для вывода ошибок STDERR.

Запустите программу wc, введите текст Good day today, нажмите Enter, введтие текст good day, нажмите Enter, нажмите Ctrl+d. Программа wc покажет статистику по количеству букв, слов и строк в вашем тексте и завершится:

> wc
good day today
good day
      2       5      24

В данном случае вы подали в STDIN программы двухстрочный текст, а в STDOUT получили три числа.

Теперь запустите команду head -n3 /etc/passwd, должно получиться примерно так:

> head -n3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin

В этом случае программа head ничего не читала из STDIN, а в STDOUT написала три строки.

Можно представить себе так: программа — это труба, в которую втекает STDIN, а вытекает STDOUT.

Важнейшее свойство юниксовой командной строки состоит в том, что программы-«трубы» можно соединять между собой: выход (STDOUT) одной программы передавать в качестве входных данных (STDIN) другой программе.

Такая конструкция из соединенных программ называется по-английски pipe (труба), по-русски — конвейер или пайп.

Объединение программ в конвейер делается символом | (вертикальная черта)

Выполните команду head -n3 /etc/passwd |wc, получится примерно следующее:

> head -n3 /etc/passwd |wc
      3       3     117

Произошло вот что: программа head выдала в STDOUT три строки текста, которые сразу же попали на вход программе wc, которая в свою очередь подсчитала количество символов, слов и строк в полученном тексте.

В конвейер можно объединять сколько угодно программ. Например, можно добавить к предыдущему конвейеру еще одну программу wc, которая подсчитает, сколько слов и букв было в выводе первой wc:

> head -n3 /etc/passwd |wc |wc
      1       3      24


Составление конвейеров (пайпов) — очень частое дело при работе в командной строке. Пример того, как это делается на практике, читайте в разделе «Составление конвейера-однострочника».

Перенаправление ввода-вывода


Вывод (STDOUT) програмы можно не только передать другой программе по конвейеру, но и просто записать в файл. Такое перенаправление делается с помощью > (знак «больше»):

date > /tmp/today.txt

В результате выполнения этой команды на диске появится файл /tmp/today.txt. Посмотрите его содержимое с помощью cat /tmp/today.txt

Если файл с таким именем уже существовал, его старое содержимое будет уничтожено. Если файл не существовал, он будет создан. Каталог, в котором создается файл, должен существовать до выполнения команды.

Если надо не перезаписать файл, а добавить вывод в его конец, используйте >>:

date >> /tmp/today.txt

Проверьте, что теперь записано в файле.

Кроме того, программе можно вместо STDIN передать любой файл. Попробуйте:

wc </etc/passwd


Что делать, когда что-то непонятно


Если вы сталкиваетесь с поведением системы, которое не понимаете, или хотите добиться определенного результата, но не знаете, как именно, советую действовать в следующем порядке (кстати, это относится не только к шеллам):

  • насколько возможно четко сформулируйте вопрос или задачу — нет ничего сложнее, чем решать «то, не знаю что»;
  • вспомните, сталкивались ли вы уже с такой же или подобной проблемой — в этом случае стоит попробовать решение, которое сработало в прошлый раз;
  • почитайте подходящие man-ы (если понимаете, какие man-ы подходят в вашем случае) — возможно, вы найдете подходящие примеры использования команд, нужные опции или ссылки на другие команды;
  • подумайте: нельзя ли немного поменять задачу? — возможно, чуть-чуть изменив условия, вы получите задачу, которую уже умеете решать;
  • задайте свой четко сформулированный вопрос в поисковой системе — возможно, ответ найдется на Stack Overflow или других сайтах;

Если ничего из перечисленного не помогло — обратитесь за советом к преподавателю, опытному коллеге или товарищу. И не бойтесь задавать «глупые» вопросы — не стыдно не знать, стыдно не спрашивать.

Если вы разобрались со сложной проблемой (самостоятельно, с помощью Интернета или других людей) — запишите свое решение на случай, если такая же проблема снова возникнет у вас или ваших товарищей. Записывать можно в простой текстовый файл, в Evernote, публиковать в соц.сетях.

Методы работы


Скопировать-и-вставить — из man-ов, из статей на StackOverflow и т.п.Командная строка состоит из текста, пользуйтесь этим: копируйте и используйте примеры команд,записывайте удачные находки на память, публикуйте их в твиттерах и блогах.

Читать man. Nuff said.

Вытащить из истории предыдущую команду, добавить в конвейер еще одну команду, запустить, повторить.См. также раздел «Составление конвейера-однострочника».

Базовые команды


  • переход в другой каталог: cd;
  • просмотр содержимого файлов: саt, less, head, tail;
  • манипуляции с файлами: cp, mv, rm;
  • просмотр содержимого каталогов: ls, ls -l, ls -lS;
  • структура каталогов: tree, tree -d (можно передать в качестве параметра каталог);
  • поиск файлов: find . -name ...;


Аналитика


  • wc, wc -l;
  • sort -k — сортировка по указанному полю;
  • sort -n — числовая соритровка;
  • diff — сравнение файлов;
  • grep, grep -v, grep -w, grep '\<word\>', grep -E — поиск текста;
  • uniq, uniq -c — уникализация строк;
  • awk — в варианте awk '{print $1}', чтобы оставить только первое поле из каждой строки, $1 можно менять на $2, $3 и т.д.;


Диагностика системы


  • ps axuww — информация о процессах (запущенных программах), работающих на машине;
  • top — интерактивный просмотр самых ресурсоемких процессов;
  • df — занятое и свободное место на диске;
  • du — суммарный размер файлов в каталоге (рекурсивно с подкаталогами);
  • strace, ktrace — какие системные вызовы выполняет процесс;
  • lsof — какие файлы использует процесс;
  • netstat -na, netstat -nap — какие порты и сокеты открыты в системе.


Некоторых программ у вас может не быть, их надо установить дополнительно. Кроме того, некоторые опции этих программ доступны только привилегированным пользователям (root‘у).

Массовое и полуавтоматическое выполнение


На первых порах пропускайте этот раздел, эти команды и конструкции понадобятся вам тогда, когда доберетесь до несложного шелльного скриптинга.

  • test — проврека условий;
  • while read — цикл по строчкам STDIN;
  • xargs — подстановка строк из STDIN в параметры указанной программе;
  • seq — генерация последовательностей натуральных чисел;
  • () — объединить вывод нескольких команд;
  • ; — выполнить одно за другим;
  • && — выполнить при условии успешного завершения первой команды;
  • || — выполнить при условии неудачного завершения первой команды;
  • tee — продублировать вывод программы в STDOUT и в файл на диске.


Разное


  • date — текущая дата;
  • curl — скачивает документ по указаному url и пишет результат на STDOUT;
  • touch — обновить дату модификации файла;
  • kill — послать процессу сигнал;
  • true — ничего не делает, возвращает истину, полезна для организации вечных циклов;
  • sudo — выполнить команду от имени root‘а.


Составление конвейера-однострочника


Давайте рассмотрим пример реальной задачи: требуется прибить все процессы task-6-server, запущенные от имени текущего пользователя.

Шаг 1.
Понять, какая программа выдает примерно нужные данные, хотя бы и не в чистом виде. Для нашей задачи стоит получить список всех процессов в системе: ps axuww. Запустить.

Шаг 2.
Посмотреть на полученные данные глазами, придумать фильтр, который выкинет часть ненужных данных. Часто это grep или grep -v. Клавишей «Вверх» вытащить из истории предыдущую команду, приписать к ней придуманный фильтр, запустить.

ps axuww |grep `whoami`

— только процессы текущего пользователя.

Шаг 3.
Повторять пункт 2, пока не получатся чистые нужные данные.

ps axuww |grep `whoami` | grep '\<task-6-server\>'

— все процессы с нужным именем (плюс, может быть, лишние вроде vim task-6-server.c и т.п.),

ps axuww |grep `whoami` | grep '\<task-6-server\>' | grep -v vim
ps axuww |grep `whoami` | grep '\<task-6-server\>' | grep -v vim
|grep -v less

— только процессы с нужным именем

ps axuww |grep `whoami` | grep '\<task-6-server\>' | grep -v vim
|grep -v less |awk '{print $2}'


— pid-ы нужных процессов, п. 3 выполнен

Шаг 4.
Применить подходящий финальный обработчик. Клавишей «Вверх» вытаскиваем из истории предыдущую команду и добавляем обработку, которая завершит решение задачи:

  • |wc -l чтобы посчитать количество процессов;
  • >pids чтобы записать pid-ы в файл;
  • |xargs kill -9 убить процессы.


Задания для тренировки


Хотите попрактиковаться в новых умениях? Попробуйте выполнить следующие задания:

  • получите список всех файлов и каталогов в вашем домашнем каталоге;
  • получите список всех man-статей из категории 2 (системные вызовы);
  • посчитайте, сколько раз в man-е по программе grep встречается слово grep;
  • посчитайте, сколько процессов запущено в данный момент от имени пользователя root;
  • найдите, какая команда встречается в максимальном количестве категорий справки (man);
  • подсчитайте, сколько раз встречается слово var на странице ya.ru.

Подсказка: вам понадобится find, grep -o, awk '{print $1}', регулярные выражения в grep, curl -s.

Что изучать дальше?


Если командная строка начинает вам нравиться, не останавливайтесь, продолжайте совершенствовать свои навыки.

Вот некоторые программы, которые определенно вам пригодятся, если вы будете жить в командной строке:

  • awk
  • sed
  • find со сложными опциями
  • apropos
  • locate
  • telnet
  • netcat
  • tcpdump
  • rsync
  • screen
  • ssh
  • tar
  • zgrep, zless
  • visudo
  • crontab -e
  • sendmail

Кроме того, со временем стоит освоить какой-нибудь скриптовый язык,например, perl или python, или даже их оба.

Кому это надо?


А стоит ли вообще изучать сегодня командную строку и шелльный скриптинг? Определенно стоит. Приведу только несколько примеров из требований Facebook к кандидатам, которые хотят поступить на работу в FB.

Data Scientist, Economic Research: Comfort with the command line and with Unix core tools; preferred: adeptness with a scripting language such as Python, or previous software engineering experience.

MySQL Database Engineer: High degree of proficiency in Shell scripting (Bash, Awk, etc); high degree of proficiency in Linux administration.

Manufacturing Quality Engineer, Server: Scripting skills in Bash, Perl, or Python is desirable.

Data Platform Engineer: 2 years experience with Unix/Linux systems.

DevOps Engineer, Data: 2 years experience with Unix/Linux system administration and programming.

Вопросы?


Если у вас есть вопросы по этой статье или вообще по работе в юниксовой командной строке, задавайте их в комментариях или по емейлу liruoko (at) yandex (dot) ru.

Немного полезных и интересных ссылок


15 интересных команд Linux

Survival guide for Unix newbies

Интересные приемы программирования на Bash
оригинал: Better Bash Scripting in 15 Minutes

Shell programming with bash: by example, by counter-example

Простые способы сделать консольную утилиту удобнее

Debug your programs like they’re closed source!

применение команд diff patch  (например надо в функциях вордпресс добавить чтобы понимал програмки от Ардуино как текстовые файлы. и сделать это без вопросов скриптом из команд обновления например)  коротко –

diff -u file1.html file2.html > patchfile.patch

patch file3.html patchfile.patch

How to use diff and patch

Shared VPS Dedicated WP Professional WP Professional Plus
The "diff" tool calculates the differences between two text files. That difference is called a patch.  You can apply a patch to another file using the "patch" tool.

diff and patch are intended to be used on text files. Files that are binary or manipulated by purpose-built applications, like .doc, .pdf, .xlsx, or .wav files, don’t work well with diff and patch.

Why use diff and patch?
Reason 1: diff can be useful by itself to see what has changed between files, even if you never use patch.

Reason 2: Sometimes you can get patches from third parties and apply them to your files. This can be beneficial in cases when the files being patched are large, but the number of changes is relatively small: transferring a patch file is more efficient than transferring the entire file.

Reason 3: You can apply patches to files that don't perfectly match the original file used in diff.

For example, if you use a CMS with a configuration file, and make local modifications to that configuration file, you want to preserve those local changes when you upgrade your CMS. Copying the vendor's new configuration over your version will lose your changes. However, in many cases, you can still safely use patch to apply the vendor's changes from the most recent version without losing your own changes.

What is diff?
diff is a way to compare files for differences (hence the name "diff") from the command line. For example, if you have an original file, then make some changes and save it under another name, you could compare the two using diff.

using diff image

diff Syntax
diff is used in the command line. The basic diff syntax looks like this:

diff [options] [original filename] [changed filename]
This command sets up the basic structure for comparing one file to another. There are also options to add more functionality to a command.

Basic Syntax (without Options)
Replace [original filename] and [changed filename] with the actual names of the files. Be sure to include the file extensions with the file names. A basic diff command without options may look something like this:

diff file1.html file2.html
In this example, the command would compare file1.html and file2.html and output the differences into the command line.

diff Syntax (with Options)
diff options add more functionality to commands. However, options will change the command syntax a little.

diff options go between diff and the first filename:

diff -y file1.html file2.html
You can also combine multiple options in one command. Do this by adding all the pertinent options’ letters after the dash (-). It will end up looking something like this:

diff -uy file1.html file2.html
You may also see a variation that gives each option its own dash (-). Both methods of adding multiple options are valid

diff -u -y file1.html file2.html
See below for a list of commonly used options:

Option	Description
-N	Ignores absent files
-r	Recursively executes diff through a directory. Used to compare multiple files at once. Note: this is not the same as -R, which is a patch option
-u	Displays output in an easier to read format. This may remove some information, such as context lines.
-y	Forces output to display differences side by side.
For more options, see this list of diff options by GNU.

diff Output
When a diff command is run, the basic output will look similar to this:

Using the -y option will change how the output is displayed

11c11
< this is text from the original file
---
> this is the same line from the second, changed file
Only changes will be displayed in the output, so you don’t have to weed through the two files. Instead, diff compares and pulls the changes out for you to view.  

Tip
The “>” and “<” characters in diff output point in the direction of the file in which the content is found. So, for the command “diff file1 file2”, a “<” refers to lines from file1 and “>” refers to lines from file2.

content tip image

How to Read diff Output
Here’s a brief guide about reading diff’s output.

The First Line of Output
The first line in the output indicates the line numbers that contain differences and the type of changes that have been made.

diff output image

If two numbers are separated by a comma, this means that there are changes from the first line number through to the second. In the example image above, 11,12 would indicate that there are changes on lines 11 - 12.

The “c” that separates the line numbers in the example above indicates the type of change that occurred. There are different letters that indicate different types of changes:

Letter	Meaning
c	Content was replaced
a	Content was added or appended
d	Content was deleted
When using patch, which will be explained in the What is patch? section, these letters will be important.

The Rest of Output
The rest of the output concerns the actual differences between files.

The changed lines will be listed next to < or > angle brackets. Three dashes (---) indicate that the end of the first file’s line changes and the beginning of the next file’s. It will look like this:

< text from file one
---
> text from file two
Now that you have a basic understanding of diff, it’s time to move on to patch.

What is patch?
patch is a command that takes the output from the diff and puts it into a file. Then, it can take the filed output and overwrite another file with with the changes. For example, a common use is to use the patch to transfer changes from the changed file to the original file, thus making them identical. While this can also be accomplished by copy/pasting the updated file into the original file, patch is much faster and efficient.

How to use diff and patch Together
diff works by cataloging the changes between the two files or folders. Patch can take those changes, put them in a file, and update older versions with it.

patch Options
The patch command also has its own set of options to add functionality. Find a list of commonly used options below:

-b	Creates a backup of the original file
-i	Forces the command to read the patch from the .patch file instead of from standard input
-p[#]	Instructs the command to strip # number of slashes from the filepath to the filename. You’ll see in most of our examples, we use -p0 so that no slashes are stripped away
-R	Reverses the previous patch
-s	Runs the command silently. It will only show process if there are errors
For more options, see this list of patch options by GNU.

Creating a patch
Creating a patch file is the first step for using patch and diff together. The patch file can be used to add changes to other files, and so it is necessary for commands like Overwrite the original file with changes.

To create a patch file, enter the command below into the command line:

diff -u file1.html file2.html > patchfile.patch
In the example above, the diff output will be saved into a file named patchfile.patch. When executing the command, be sure to change file1.html and file2.html to actual file names.

Overwrite files with changes
Once the patch file is created, you can use it to copy the changes to another file. For example, you may want to overwrite file1 with the changes from the updated file2. To do this, you could use syntax like this:

patch file1.html patchfile.patch
Replace file1.html with your original file. This would overwrite the old contents of file1.html with the changed contents of file2.html.

How to Reverse a patch
If you want to revert the file to its previous version before patching, you can do so by running this command:

patch -p0 -R -i patchfile.patch
The command line will then prompt you to input the name of the file you want to revert. Once the filename has been entered, the reversing process will begin. If successful, the file will be reverted to its previous state.

patch Directories
Using diff and patch on whole directories is a similar process to using it on single files.

The first step is to create a patch file by using the command:

diff -ruN folder1/ folder2/ > patchfile.patch
Then, you would issue the command to patch the original folder, which in this case is folder1:

patch -s -p0 < patchfile.patch
If successful, your original directory should now be updated to match the second, updated folder.

Updated on February 6, 2019
Was this article helpful?
Yes No
Related Articles
Downloading files with curl
Downloading files with wget
Using kill, killall, and pkill
Viewing Files with cat and more
Using gzip
Using du and df

Related Articles

пример использования команд из терминала

или настройка сервера vps на французском хостинге

(совпадения для поиска php8 mysql57 centos 7 mysql-community-server nginx) freebsd будет еще авто скрипт с настройкой и обновлением графического экрана gnome4 да еще и с использованием мощных видеоплат radeon 580 nvidia 1060 – как игрушки так и разработка с майнингом и криптовалютой.

wordpress password reset сброс пароля вордпресс primer

просьба использовать по назначенью – то есть с обучающими целями. Хосты и адреса реальные, дидосить их не надо.

не работает - не те пакеты

[root@98868 yum.repos.d]# history
    1  yum install nginx php8
    2  yum install  php
    3  yum install  php7
    4  yum install mysql57-server
    5  yum install mysql-server
    6  yum install mysql
    7  yum install  php81
    8  yum search php
    9  mc
   10  exit
   11  yum-config-manager --enable nginx-mainline
   12  yum search nginx
   13  yum install nginx
   14  yum install  https://rpms.remirepo.net/enterprise/remi-release-8.rpm
   15  yum install  epel-release
   16  yum install  https://rpms.remirepo.net/enterprise/remi-release-8.rpm
   17  yum install --skip-broken  https://rpms.remirepo.net/enterprise/remi-release-8.rpm
   18  yum install  epel-release
   19  tar xvf 
   20  tar xvf
   21  tar xvf sv-20-Август-2019.tar.gz
   22  uname -a
   23  yum-config-manager --enable mysql
   24  yum-config-manager --enable mysql-community
   25  yum install  mysql
   26  yum install --skip-broken mysql
   27  yum-config-manager --enable mysql80-community
   28  yum install --skip-broken mysql
   29  yum-config-manager --enable mysql80-community
   30  yum install --skip-broken mysql
   31  yum install nginx
   32  yum upgrade
   33  yum repo upgrade
   34  yum --skip-broken upgrade
   35  yum install openssl11-libs
   36  yum install mysql-community-libs
   37  yum --skip-broken upgrade
   38  yum erase mariadb-libs.x86_64 1:5.5.68-1.el7
   39  yum --skip-broken upgrade
   40  yum install mysql-community-libs
   41  rpm -Va --nofiles --nodigest
   42  yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
   43  yum erase epel-release-latest-7.noarch.rpm
   44  yum erase epel-release-latest-7.noarch
   45  yum erase epel-release-latest-7
   46  rm /var/tmp/yum-root-kMIBn7/epel-release-latest-7.noarch.rpm
   47  yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
   48  yum erase epel-release-7-14
   49  yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
   50  yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
   51  yum -y install yum-utils
   52  yum -y install yum-utils
   53  yum-config-manager --disable 'remi-php*'
   54  yum-config-manager --enable remi-php80
   55  yum  install php8
   56  yum  install php80
   57  yum -y install mysql
   58  yum erase mysql-community-server
   59  yum erase mysql
   60  yum install nginx
   61  yum install php80
   62  yum install php php-cli php-common php-fpm
   63  yum install php-mysqlnd
   64  php -v
   65  rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7-3.noarch.rpm
   66  sed -i 's/enabled=1/enabled=0/' /etc/yum.repos.d/mysql-community.repo
   67  yum --enablerepo=mysql80-community install mysql-community-server
   68  yum --enablerepo=mysql80-community install mysql-community-server --skip-bro0ken
   69  yum --enablerepo=mysql80-community install mysql-community-server --skip-broken
   70  yum  install libaio --skip-broken
   71  yum  install mysql-community-client --skip-broken
   72  yum --enablerepo=mysql80-community install mysql-community-icu-data-files --skip-broken
   73  yum --enablerepo=mysql80-community
   74  yum-config-manager --disable mysql80-community
   75  yum-config-manager --enable mysql80-community
   76  yum  install mysql-community-client --skip-broken
   77  yum  install mysql-community-common --skip-broken
   78  yum erase mysql80-community-release-el7-1.noarch
   79  yum erase mysql80-community-release-el7-1
   80  rpm -Uvh
   81  yum upgrade
   82  yum update --skip-broken
   83  yum localinstall https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
   84  yum update --skip-broken
   85  yum erase mysql80-community-release
   86  yum list installed |grep mysql
   87  yum  install mysql-community-common
   88  yum  install mysql-community-release
   89  yum  install mysql-community-client
   90  yum-config-manager --enable mysql80-community
   91  yum-config-manager --enable mysql80
   92  yum-config-manager --enable  mysql80-community-release
   93  yum --enablerepo=mysql80-community install mysql-community-server
   94  yum localinstall https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
   95  yum --enablerepo=mysql80-community install mysql-community-server
   96  yum --enablerepo=mysql80-community install --skip-broken mysql-community-server
   97  yum --enablerepo=mysql80-community
   98  yum-config-manager --enable  mysql80-community
   99  yum install mysql-community-client
  100  yum install mysql-community-common
  101  yum --disablerepo=mysql80-community --enablerepo=mysql57-community install mysql-community-server
  102  service mysqld start
  103  service mysql-server start
(ошибки)
  104  yum --disablerepo=mysql80-community --enablerepo=mysql57-community install mysql-community-server
  105  rm etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
  106  rm /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
  107  yum-config-manager --disable  mysql80-community
  108  yum-config-manager --enable  mysql57-community
  109  yum install mysql-community-server
  110  yum --enablerepo=mysql57-community install mysql-community-server
  111  yum-config-manager --enable  mysql57-community
  112  OA
  113  yum-config-manager --enable  mysql57-community
  114  yum  install mysql-community-server

   30  yum install --skip-broken mysql-community-server
   31  wget https://repo.mysql.com/RPM-GPG-KEY-mysql
   32  mc


The GPG keys listed for the "MySQL 5.7 Community Server" repository are already installed but they are not correct for this package. Check that the correct key URLs are configured for this repository.

 

You have several options to fix this:

    Disable the gpg check in the repository by changing "gpgcheck=1" into "gpgcheck=0"
    Reimport the key using below command:
    rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
    You might need to redownload the latest key for the repo, in this case from:
    https://repo.mysql.com/RPM-GPG-KEY-mysql

yum --enablerepo=mysql57-community install mysql-community-server
(лучше включить дистрибутив сначала как выше, а то не тот ключ загрузится)


Starting MySQL 8 Service on CentOS 7

For CentOS 7, use systemd to start mysql service:

sudo systemctl enable  --now mysqld.service



php80
https://www.tecmint.com/install-php-8-on-centos/

yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install -y --enablerepo=remi-php80 php php-cli

OR

Enable Remi PHP 8.0 repository permanently with yum-config-manager command and then install PHP v8.0.

yum install -y yum-utils

yum-config-manager --enable remi-php80

yum install -y php php-cli





Step 3. Start MySQL Service

Use this command to start mysql service:

service mysqld start

Step 4. Show the default password for root user

When you install MySQL 8.0, the root user account is granted a temporary password. To show the password of the root user account, you use this command:

grep "A temporary password" /var/log/mysqld.log
Code language: JavaScript (javascript)

Here is the output:

[Note] A temporary password is generated for root@localhost: hjkygMukj5+t783

Note that your temporary password will be different. You will need this password for changing the password of the root user account.
Step 5. MySQL Secure Installation

Execute the command mysql_secure_installation to secure MySQL server:

mysql_secure_installation

It will prompt you for the current password of the root account:

Enter password for user root:

Enter the temporary password above and press Enter. The following message will show:

The existing password for the user account root has expired. Please set a new password.

New password:
Re-enter new password:
Code language: PHP (php)

You will need to enter the new password for the root‘s account twice. It will prompt for some questions, it is recommended to type yes (y):

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

Step 6. Restart and enable the MySQL service

Use the following command to restart the mysql service:

service mysqld restart

and autostart mysql service on system’s startup:

chkconfig mysqld on


немножко не так


root@98868 etc]# systemctl enable php-fpm.service
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
[root@98868 etc]# 
[root@98868 nginx]# OA
bash: OA: команда не найдена

[root@98868 nginx]# chmod -R 777 *

[root@98868 nginx]# chown -R www:www *

[root@98868 www]# mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
[root@98868 www]# systemctl enable mysqld.service
[root@98868 www]# service mysqld start
Redirecting to /bin/systemctl start mysqld.service
[root@98868 www]# grep "A temporary password" /var/log/mysqld.log
заводим временный пароль
mysql> show databases;
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql> ALTER USER root@localhost IDENTIFIED BY '123123q'
    -> ;
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
mysql> ALTER USER root@localhost IDENTIFIED BY 'm2Z123123q!Qz87'
    -> ;
Query OK, 0 rows affected (0,00 sec)

mysql> 





Step 7. Connect to MySQL

Use this command to connect to MySQL server:

mysql -u root -p

It will prompt you for the password of the root user. You type the password and press Enter:

Enter password:

It will show the mysql command:

mysql>

Use the SHOW DATABASESto display all databases in the current server:

mysql> show databases;
Code language: SQL (Structured Query Language) (sql)

Here is the output:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.05 sec)
Code language: JavaScript (javascript)

In this tutorial, you have learned step by step how to install MySQL 8 on CentOS 7.

Your MySQL connection id is 5
Server version: 5.7.38 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
легче
mysql> create USER mege@localhost;
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
mysql> create USER mege@localhost IDENTIFIED BY 'a123123q!Qz89';
Query OK, 0 rows affected (0,00 sec)

mysql> create USER svetan@localhost IDENTIFIED BY 'b123123q!Qz87Z';
Query OK, 0 rows affected (0,00 sec)

mysql> create database svetan;
Query OK, 1 row affected (0,00 sec)

mysql> create database megeraru;
Query OK, 1 row affected (0,00 sec)

mysql> use svetan;
Database changed
mysql> grant all to svetan@localhost;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versлегчеion for the right syntax to use near 'to svetan@localhost' at line 1
mysql> GRANT ALL PRIVILEGES ON  * TO 'svetan'@'localhost';
Query OK, 0 rows affected (0,01 sec)

mysql> use megeraru;
Database changed
mysql> GRANT ALL PRIVILEGES ON  * TO 'mege'@'localhost';
Query OK, 0 rows affected (0,00 sec)

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> exit
Bye
[root@98868 www]# 
теперь надо восстановить базу из архива, сайт переносится

[root@98868 www]# mysql mege <me-copy.sql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
[root@98868 www]# mysql -p mege <me-copy.sql
Enter password: 
[root@98868 www]# mysql -p svetan <sv.sql
Enter password: 
[root@98868 www]# 
если не ругается (а может если особенно версии разные) значит получилось
еще хост и пароли редактировать в файлах настройки вордпресс и пхпбб

еще модули для php и его часть настройки www.conf сколько там серверов и под каким пользователем запускать
пользователь и группа www сделана путем редактирования из под рута файлов passwd gshadow group
но это прием хакера, легче набрать в консоле adduser (adduser -U)

mysql 5.7 а не 8 он легче

nginx еще пример
как видно, сайт не использует apache а использует движок Российского программиста.

[root@98868 www]# service php-fpm status
Redirecting to /bin/systemctl status php-fpm.service
● php-fpm.service - The PHP FastCGI Process Manager
   Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
   Active: active (running) since Ср 2022-06-08 11:07:09 EDT; 2h 42min ago
 Main PID: 11631 (php-fpm)
   Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
   CGroup: /system.slice/php-fpm.service
           ├─11631 php-fpm: master process (/etc/php-fpm.conf)
           ├─11632 php-fpm: pool www
           └─11633 php-fpm: pool www

июн 08 11:07:09 98868.ip-ns.net systemd[1]: Starting The PHP FastCGI Process Manager...
июн 08 11:07:09 98868.ip-ns.net systemd[1]: Started The PHP FastCGI Process Manager.
[root@98868 www]# service nginx status
Redirecting to /bin/systemctl status nginx.service
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: http://nginx.org/en/docs/
[root@98868 www]# service mysqld status
Redirecting to /bin/systemctl status mysqld.service
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: active (running) since Ср 2022-06-08 13:01:50 EDT; 48min ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
  Process: 14470 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
  Process: 14417 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
 Main PID: 14473 (mysqld)
   CGroup: /system.slice/mysqld.service
           └─14473 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

июн 08 13:01:45 98868.ip-ns.net systemd[1]: Starting MySQL Server...
июн 08 13:01:50 98868.ip-ns.net systemd[1]: Started MySQL Server.
[root@98868 www]# 

исправляем конфиг и где там ошибки смотрим - может быть разные настройки или порты
root@98868 sites-enabled]# service nginx start
Redirecting to /bin/systemctl start nginx.service
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
[root@98868 sites-enabled]# systemctl status nginx.service
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Ср 2022-06-08 14:03:34 EDT; 2s ago
     Docs: http://nginx.org/en/docs/
  Process: 15123 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=1/FAILURE)

июн 08 14:03:34 98868.ip-ns.net systemd[1]: Starting nginx - high performance web server...
июн 08 14:03:34 98868.ip-ns.net nginx[15123]: nginx: [emerg] bind() to 0.0.0.0:91 failed (13: Permission denied)
июн 08 14:03:34 98868.ip-ns.net systemd[1]: nginx.service: control process exited, code=exited status=1
июн 08 14:03:34 98868.ip-ns.net systemd[1]: Failed to start nginx - high performance web server.
июн 08 14:03:34 98868.ip-ns.net systemd[1]: Unit nginx.service entered failed state.
июн 08 14:03:34 98868.ip-ns.net systemd[1]: nginx.service failed.
[root@98868 sites-enabled]# service nginx start
Redirecting to /bin/systemctl start nginx.service
[root@98868 sites-enabled]# 

[root@98868 sites-enabled]# systemctl enable nginx.service
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@98868 sites-enabled]# 

автозапуск
 ошибки еще

022/06/08 14:04:37 [notice] 15150#15150: getrlimit(RLIMIT_NOFILE): 1024:4096
2022/06/08 14:04:37 [notice] 15151#15151: start worker processes
2022/06/08 14:04:37 [notice] 15151#15151: start worker process 15152
2022/06/08 14:04:37 [alert] 15152#15152: setrlimit(RLIMIT_NOFILE, 240000) failed (1: Operation not permitted)
2022/06/08 14:04:37 [notice] 15151#15151: start worker process 15153
закомментировать в настройках - это просто от старой версии
2022/06/08 14:05:37 [notice] 15155#15155: http file cache: /var/run/nginx-cache 0.000M, bsize: 4096
2022/06/08 14:05:37 [notice] 15151#15151: signal 17 (SIGCHLD) received from 15155
2022/06/08 14:05:37 [notice] 15151#15151: cache loader process 15155 exited with code 0
2022/06/08 14:05:37 [notice] 15151#15151: signal 29 (SIGIO) received
прав доступа нет и /run 777 проверить
2022/06/08 14:05:37 [notice] 15155#15155: http file cache: /var/run/nginx-cache 0.000M, bsize: 4096
2022/06/08 14:05:37 [notice] 15151#15151: signal 17 (SIGCHLD) received from 15155
2022/06/08 14:05:37 [notice] 15151#15151: cache loader process 15155 exited with code 0
2022/06/08 14:05:37 [notice] 15151#15151: signal 29 (SIGIO) received
[root@98868 sites-enabled]# service nginx restart
Redirecting to /bin/systemctl restart nginx.service
[root@98868 sites-enabled]# service php-fpm restart
Redirecting to /bin/systemctl restart php-fpm.service
[root@98868 sites-enabled]# 
[root@98868 ~]# chown -R www:www *
[root@98868 ~]# ls
anaconda-ks.cfg  pki  RPM-GPG-KEY-mysql  yum.repos.d
[root@98868 ~]# chown -R root root *
chown: cannot access ‘root’: No such file or directory
[root@98868 ~]# chown -R root:root *
[root@98868 ~]# mc

[root@98868 nginx]#  ps aux | grep nginx
root       766  0.0  0.0 152336  1444 ?        Ss   14:31   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
www        770  0.0  0.1 152340  2184 ?        S    14:31   0:00 nginx: worker process
www        773  0.0  0.1 152652  2900 ?        S    14:31   0:00 nginx: worker process
www        774  0.0  0.1 152340  1928 ?        S    14:31   0:00 nginx: cache manager process
root      1101  0.0  0.0 112812   980 pts/1    S+   14:37   0:00 grep --color=auto nginx
[root@98868 nginx]# 
(настройка user www www;)
selinux отключить!
[root@98868 www]# 
[root@98868 svetan]# getenforce
Enforcing
[root@98868 svetan]# setenforce Permissive
[root@98868 svetan]# 
[root@98868 svetan]# chcon -Rt httpd_sys_content_t /var/www
[root@98868 svetan]# getenforce
Permissive
[root@98868 svetan]# restorecon -r /var/www
[root@98868 svetan]# getenforce
Permissive
[root@98868 svetan]# 
[root@98868 www]# 
еще проще

1

I solved it by disable SELINUX and reboot

mcedit /etc/selinux/config

#SELINUX=enforcing
SELINUX=disabled

настройка https
(Y)es/(N)o: y
Account registered.
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): svetan.ru www.svetan.ru
Requesting a certificate for svetan.ru and www.svetan.ru
Performing the following challenges:
http-01 challenge for svetan.ru
http-01 challenge for www.svetan.ru
Cleaning up challenges
Problem binding to port 80: Could not bind to IPv4 or IPv6.
[root@98868 ~]# service nginx stop
Redirecting to /bin/systemctl stop nginx.service
[root@98868 ~]# certbot certonly
Saving debug log to /var/log/letsencrypt/letsencrypt.log

How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Spin up a temporary webserver (standalone)
2: Place files in webroot directory (webroot)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1
Plugins selected: Authenticator standalone, Installer None
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): svetan.ru www.svetan.ru
Requesting a certificate for svetan.ru and www.svetan.ru
Performing the following challenges:
http-01 challenge for svetan.ru
http-01 challenge for www.svetan.ru
Waiting for verification...
Cleaning up challenges
Subscribe to the EFF mailing list (email: santosha@svetan.ru).
Starting new HTTPS connection (1): supporters.eff.org

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/svetan.ru/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/svetan.ru/privkey.pem
   Your certificate will expire on 2022-09-06. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again. To non-interactively renew *all* of your
   certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

[root@98868 ~]# certbot certonly
Saving debug log to /var/log/letsencrypt/letsencrypt.log

How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Spin up a temporary webserver (standalone)
2: Place files in webroot directory (webroot)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1
Plugins selected: Authenticator standalone, Installer None
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): megera.org www.megera.org
Requesting a certificate for megera.org and www.megera.org
Performing the following challenges:
http-01 challenge for megera.org
http-01 challenge for www.megera.org
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/megera.org/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/megera.org/privkey.pem
   Your certificate will expire on 2022-09-06. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again. To non-interactively renew *all* of your
   certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

yum install php-mbstring

session_start(): Failed to read session data: files (path: /var/lib/php/session)
cd /var/lib/php
 chown -R www:www *
chmod 644 /var/www/phpMyAdmin/config.inc.php


[root@98868 ~]# service nginx restart
Redirecting to /bin/systemctl restart nginx.service
[root@98868 ~]# 
открываем phpadmin и в пользователе админ меняем хеш пароля. в новой версии поменялось шифрование md5 salt возможно sha256 как у биткоина например $_P$CBCT3rb3sulME74PIh4EIp5U4f9HYby/

 chmod 777 /var/www/phpMyAdmin/config.inc.php для безопасности
из консоли mysql (тоже надо знать пароль к mysql)
Through MySQL Command Line

    Get an MD5 hash of your password.
        Visit md5 Hash Generator, or…
        Create a key with Python, or…
        On Unix/Linux:
            Create a file called wp.txt, containing nothing but the new password.
            tr -d ‘\r\n’ < wp.txt | md5sum | tr -d ‘ -‘
            rm wp.txt
        On Mac OS X:
            Create a file called wp.txt, containing nothing but the new password. Then enter either of the lines below
            md5 -q ./wp.txt; rm ./wp.txt (If you want the MD5 hash printed out.)
            md5 -q ./wp.txt | pbcopy; rm ./wp.txt (If you want the MD5 hash copied to the clipboard.)
    “mysql -u root -p” (log in to MySQL)
    enter your mysql password
    “use (name-of-database)” (select WordPress database)
    “show tables;” (you’re looking for a table name with “users” at the end)
    “SELECT ID, user_login, user_pass FROM (name-of-table-you-found);” (this gives you an idea of what’s going on inside)
    “UPDATE (name-of-table-you-found) SET user_pass=”(MD5-string-you-made)” WHERE ID = (id#-of-account-you-are-reseting-password-for);” (actually changes the password)
    “SELECT ID, user_login, user_pass FROM (name-of-table-you-found);” (confirm that it was changed)
    (type Control-D to exit mysql client)

Note: if you have a recent version of MySQL (version 5.x?) you can have MySQL compute the MD5 hash for you.

    Skip step# 1 above.
    Do the following for step# 7 instead.
        “UPDATE (name-of-table-you-found) SET user_pass = MD5(‘(new-password)’) WHERE ID = (id#-of-account-you-are-reseting-password-for);” (actually changes the password)

Note that even if the passwords are salted, meaning they look like $P$BLDJMdyBwegaCLE0GeDiGtC/mqXLzB0, you can still replace the password with an MD5 hash, and WordPress will let you log in.


... работает  service php-fpm start service nginx start service mysqld start
LAMP LEMP linux mysql php на чистом (новом) сервере - получается рабочий хостинг сайта
пример сложный - ошибка с выбором пакета для centos8 а оказался у французи centos7 - midnight commander и просмотр файлов показали какая версия а команда uname посчитала за непонятный линукс. еще будет доустановка софта для картинок видео и каталогов вордпресс wordpress  и модулей php   да это рабочий вариант по шагам и надо только пароли поменять и имена пользователей и адреса.
www.svetan.ru 

командная строка необходима для освоения крипты ( а не только тыкать мышой на кнопку все потратить)

запустить кино на большом экране проектора vlc MPEG.DAT

поможет для ведения сайта, хостинга, для программирования, изучения компьютера .

На телефоне даже есть.

выложить информацию на ftp например, перебросить видео с карты памяти и многое другое, администрирование систем.

Студентам обязательно, в совместном предприятии с американцами учил – типа компьютерные курсы в СССР, в 89-м . Преподавал один известный американский профессор, программист и компьютерщик, показывал языки программирования и командную оболочку, тогда DOS операционную систему на дискетках. Сейчас ее повторяет командная строка Windows 10 и Powershell в 11-й винде, большинство команд те же. На Линуксе сложнее даже, а работать с ней – проще, особенности надо знать.