-atime n True если прошло n дней с создания файла.
-mtime n True если файл был изменен n дней назад.
-exec command Выполнить команду если в поиске пришло true. Завершение команды должно быть отмечено знаком ";". Аргумент для команды {} заменяется найденым путем к файлу.
find /space/*.gz -mtime 28 -exec rm {} \;
Найти архивы gzip в разделе /space/ созданные ранее чем 28 дней и стереть.
JunOS, IOS, Unix, Linux, Windows, routing, switching, security, QoS, network design, telecom.. Статьи, заметки. Решил собрать блог, чтоб разместить полезные статьи в одном месте.
четверг, 26 ноября 2009 г.
среда, 25 ноября 2009 г.
Почистить транзакционные логи MySQL
12.6.1.1. PURGE BINARY LOGS Syntax
PURGE { BINARY | MASTER } LOGS
{ TO 'log_name' | BEFORE datetime_expr }
The binary log is a set of files that contain information about data modifications made by the MySQL server. The log consists of a set of binary log files, plus an index file.
The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date. The log files also are removed from the list recorded in the index file, so that the given log file becomes the first.
This statement has no effect if the --log-bin option has not been enabled.
Examples:
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';
The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value (a value in 'YYYY-MM-DD hh:mm:ss' format). BINARY and MASTER are synonyms.
This statement is safe to run while slaves are replicating. You do not need to stop them. If you have an active slave that currently is reading one of the logs you are trying to delete, this statement does nothing and fails with an error. However, if a slave is dormant and you happen to purge one of the logs it has yet to read, the slave will be unable to replicate after it comes up.
To safely purge logs, follow this procedure:
1.
On each slave server, use SHOW SLAVE STATUS to check which log it is reading.
2.
Obtain a listing of the binary logs on the master server with SHOW BINARY LOGS.
3.
Determine the earliest log among all the slaves. This is the target log. If all the slaves are up to date, this is the last log on the list.
4.
Make a backup of all the logs you are about to delete. (This step is optional, but always advisable.)
5.
Purge all logs up to but not including the target log.
You can also set the expire_logs_days system variable to expire binary log files automatically after a given number of days (see Section 5.1.3, “Server System Variables”). If you are using replication, you should set the variable no lower than the maximum number of days your slaves might lag behind the master.
Prior to MySQL 5.0.60, PURGE BINARY LOGS TO and PURGE BINARY LOGS BEFORE did not behave in the same way (and neither one behaved correctly) when binary log files listed in the .index file had been removed from the system by some other means (such as using rm on Linux). Beginning with MySQL 5.0.60, both variants of the statement fail with an error in such cases. (Bug#18199, Bug#18453) You can handle such errors by editing the .index file (which is a simple text file) manually and insuring that it lists only the binary log files that are actually present, then running again the PURGE BINARY LOGS statement that failed.
PURGE { BINARY | MASTER } LOGS
{ TO 'log_name' | BEFORE datetime_expr }
The binary log is a set of files that contain information about data modifications made by the MySQL server. The log consists of a set of binary log files, plus an index file.
The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date. The log files also are removed from the list recorded in the index file, so that the given log file becomes the first.
This statement has no effect if the --log-bin option has not been enabled.
Examples:
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';
The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value (a value in 'YYYY-MM-DD hh:mm:ss' format). BINARY and MASTER are synonyms.
This statement is safe to run while slaves are replicating. You do not need to stop them. If you have an active slave that currently is reading one of the logs you are trying to delete, this statement does nothing and fails with an error. However, if a slave is dormant and you happen to purge one of the logs it has yet to read, the slave will be unable to replicate after it comes up.
To safely purge logs, follow this procedure:
1.
On each slave server, use SHOW SLAVE STATUS to check which log it is reading.
2.
Obtain a listing of the binary logs on the master server with SHOW BINARY LOGS.
3.
Determine the earliest log among all the slaves. This is the target log. If all the slaves are up to date, this is the last log on the list.
4.
Make a backup of all the logs you are about to delete. (This step is optional, but always advisable.)
5.
Purge all logs up to but not including the target log.
You can also set the expire_logs_days system variable to expire binary log files automatically after a given number of days (see Section 5.1.3, “Server System Variables”). If you are using replication, you should set the variable no lower than the maximum number of days your slaves might lag behind the master.
Prior to MySQL 5.0.60, PURGE BINARY LOGS TO and PURGE BINARY LOGS BEFORE did not behave in the same way (and neither one behaved correctly) when binary log files listed in the .index file had been removed from the system by some other means (such as using rm on Linux). Beginning with MySQL 5.0.60, both variants of the statement fail with an error in such cases. (Bug#18199, Bug#18453) You can handle such errors by editing the .index file (which is a simple text file) manually and insuring that it lists only the binary log files that are actually present, then running again the PURGE BINARY LOGS statement that failed.
вторник, 10 ноября 2009 г.
Perl и время
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
$year=$year+1900;
$mon=$mon+1;
print "$year-$mon-$mday $hour:$min:$sec";
print "\n";
$year=$year+1900;
$mon=$mon+1;
print "$year-$mon-$mday $hour:$min:$sec";
print "\n";
пятница, 6 ноября 2009 г.
Solaris и время
Открываем
bash-2.05# cat /etc/default/init
#ident "@(#)init.dfl 1.6 00/05/27 SMI"
#
# This file is /etc/default/init. /etc/TIMEZONE is a symlink to this file.
# This file looks like a shell script, but it is not. To maintain
# compatibility with old versions of /etc/TIMEZONE, some shell constructs
# (i.e., export commands) are allowed in this file, but are ignored.
#
# Lines of this file should be of the form VAR=value, where VAR is one of
# TZ, LANG, CMASK, or any of the LC_* environment variables.
#
TZ=Europe/Moscow
CMASK=022
LC_COLLATE=en_US.ISO8859-1
LC_CTYPE=en_US.ISO8859-1
LC_MESSAGES=C
LC_MONETARY=en_US.ISO8859-1
LC_NUMERIC=en_US.ISO8859-1
LC_TIME=en_US.ISO8859-1
Смотрим, какие переменные подгружены в среду
bash-2.05# export
declare -x HOME="/"
declare -x HOSTNAME="ddslsrostov"
declare -x HOSTTYPE="sparc"
declare -x HZ=""
declare -x LOGNAME="root"
declare -x MACHTYPE="sparc-sun-solaris2.9"
declare -x OLDPWD="/u01/fw_data/bypass"
declare -x OSTYPE="solaris2.9"
declare -x PATH="/usr/sbin:/usr/bin"
declare -x PWD="/etc/default"
declare -x SHELL="/sbin/sh"
declare -x SHLVL="1"
declare -x TERM="xterm"
declare -x TZ="Europe/Moscow"
:)
bash-2.05# cat /etc/default/init
#ident "@(#)init.dfl 1.6 00/05/27 SMI"
#
# This file is /etc/default/init. /etc/TIMEZONE is a symlink to this file.
# This file looks like a shell script, but it is not. To maintain
# compatibility with old versions of /etc/TIMEZONE, some shell constructs
# (i.e., export commands) are allowed in this file, but are ignored.
#
# Lines of this file should be of the form VAR=value, where VAR is one of
# TZ, LANG, CMASK, or any of the LC_* environment variables.
#
TZ=Europe/Moscow
CMASK=022
LC_COLLATE=en_US.ISO8859-1
LC_CTYPE=en_US.ISO8859-1
LC_MESSAGES=C
LC_MONETARY=en_US.ISO8859-1
LC_NUMERIC=en_US.ISO8859-1
LC_TIME=en_US.ISO8859-1
Смотрим, какие переменные подгружены в среду
bash-2.05# export
declare -x HOME="/"
declare -x HOSTNAME="ddslsrostov"
declare -x HOSTTYPE="sparc"
declare -x HZ=""
declare -x LOGNAME="root"
declare -x MACHTYPE="sparc-sun-solaris2.9"
declare -x OLDPWD="/u01/fw_data/bypass"
declare -x OSTYPE="solaris2.9"
declare -x PATH="/usr/sbin:/usr/bin"
declare -x PWD="/etc/default"
declare -x SHELL="/sbin/sh"
declare -x SHLVL="1"
declare -x TERM="xterm"
declare -x TZ="Europe/Moscow"
:)
вторник, 15 сентября 2009 г.
Как использовать test
Evaluate a conditional expression expr.
Syntax
test expr
[ expr
Options
Each operator and operand must be a separate argument. When the [ form is used, the last argument to the command must be a ]. Expressions may be combined using the following operators, listed in decreasing order of precedence.
! expr
True if expr is false.
( expr )
Returns the value of expr. This may be used to override the
normal precedence of operators.
expr1 -a expr2
True if both expr1 and expr2 are true.
expr1 -o expr2
True if either expr1 or expr2 is true.
The test and [ builtins evaluate conditional expressions using a set of rules based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
2 arguments
If the first argument is `!', the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators, the expression is true if the unary test is true. If the first argument is not a valid unary operator, the expression is false.
3 arguments
If the second argument is one of the binary conditional operators, the result of the expression is the result of the binary test using the first and third arguments as operands. If the first argument is `!', the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly `(' and the third argument is exactly `)', the result is the one-argument test of the second argument. Otherwise, the expression is false. The `-a' and `-o' operators are considered binary operators in this case.
4 arguments
If the first argument is `!', the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above.
5 or more arguments
The expression is parsed and evaluated according to precedence using the rules listed above.
The above applies to the BOURNE shell built-in, the BASH `test' command has the following additional options:
File type tests
These options test for particular types of files. All cases will only return True (0) if the file exists.
`-b file'
True if file is a Block special device.
`-c file'
True if file is a Character special device.
`-d file'
True if file is a Directory.
`-e file'
True if file Exists.
`-f file'
True if file is a regular File.
`-g file'
True if file has its set-group-id bit set.
`-G file'
True if file is owned by the current effective group id.
`-k file'
True if file has its "sticky" bit set.
`-h file'
`-L file'
True if file is a symbolic Link.
`-O file'
True if file is owned by the current effective user id.
`-p file'
True if file is a named Pipe.
`-r file'
True if file is readable.
`-S file'
True if file is a Socket.
`-s file'
True if file has a Size greater than zero.
`-t [FD]'
True if FD is opened on a terminal. If FD is omitted, it defaults
to 1 (standard output).
`-u file'
True if file has its set-user-id bit set.
`-w file'
True if file is writable.
`-x file'
True if file is executable.
`file1 -ef file2'
True if file1 and file2 have the same device and inode numbers,
i.e., if they are hard links to each other.
File Age
These options test the file modification date.
`file1 -nt file2'
True if file1 is newer than file2.
`file1 -ot file2'
True if file1 is older than file2.
String tests
These options test string characteristics. Strings are not quoted for `test', though you may need to quote them to protect characters with special meaning to the shell, e.g., spaces.
`-z String'
True if the length of String is zero.
`-n String'
`String'
True if the length of String is nonzero.
`String1 = String2'
True if the strings are equal.
`String1 != String2'
True if the strings are not equal.
Numeric tests
Numeric relationals. The arguments must be entirely numeric (possibly negative), or the special expression `-l STRING', which evaluates to the length of STRING.
`ARG1 -eq ARG2'
`ARG1 -ne ARG2'
`ARG1 -lt ARG2'
`ARG1 -le ARG2'
`ARG1 -gt ARG2'
`ARG1 -ge ARG2'
These arithmetic binary operators return true if ARG1 is equal,
not-equal, less-than, less-than-or-equal, greater-than, or
greater-than-or-equal than ARG2, respectively.
For example:
test -1 -gt -2 && echo yes
=> yes
test -l abc -gt 1 && echo yes
=> yes
test 0x100 -eq 1
error--> test: integer expression expected before -eq
Examples
$ ls -al
total 67
drwxr-xr-x 18 root root 4096 Jun 9 21:12 ./
drwxr-xr-x 18 root root 4096 Jun 9 21:12 ../
-rw-rw-rw- 1 simon users 4096 Jun 9 07:30 london
-rwsrwsrwx 1 simon users 4096 Jun 9 07:32 aberdeen
-rw------- 1 simon users 4096 Jun 9 07:29 bristol
-rw-r--r-- 1 simon users 4096 Jun 9 07:29 bath
$
$ test -r paris
$ echo $?
1
$
Because the file `paris' is not Readable, the value returned is false (non zero)
if [ "$LOGNAME" = "scott" ]
then
echo "Logged in as Scott"
else
echo "incorrect user"
fi
If the logname variable = scott then the test returns TRUE (0)
"The test of a vocation is the love of the drudgery it involves" - Logan Pearsall
Related:
case - Conditionally perform a command
cmp - Compare two files
expr - Evaluate expressions
eval - Evaluate several commands/arguments
for - Expand words, and execute commands
if - Conditionally perform a command
pathchk - Check file name portability
Equivalent Windows command: IF - Conditionally perform a command
Syntax
test expr
[ expr
Options
Each operator and operand must be a separate argument. When the [ form is used, the last argument to the command must be a ]. Expressions may be combined using the following operators, listed in decreasing order of precedence.
! expr
True if expr is false.
( expr )
Returns the value of expr. This may be used to override the
normal precedence of operators.
expr1 -a expr2
True if both expr1 and expr2 are true.
expr1 -o expr2
True if either expr1 or expr2 is true.
The test and [ builtins evaluate conditional expressions using a set of rules based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
2 arguments
If the first argument is `!', the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators, the expression is true if the unary test is true. If the first argument is not a valid unary operator, the expression is false.
3 arguments
If the second argument is one of the binary conditional operators, the result of the expression is the result of the binary test using the first and third arguments as operands. If the first argument is `!', the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly `(' and the third argument is exactly `)', the result is the one-argument test of the second argument. Otherwise, the expression is false. The `-a' and `-o' operators are considered binary operators in this case.
4 arguments
If the first argument is `!', the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above.
5 or more arguments
The expression is parsed and evaluated according to precedence using the rules listed above.
The above applies to the BOURNE shell built-in, the BASH `test' command has the following additional options:
File type tests
These options test for particular types of files. All cases will only return True (0) if the file exists.
`-b file'
True if file is a Block special device.
`-c file'
True if file is a Character special device.
`-d file'
True if file is a Directory.
`-e file'
True if file Exists.
`-f file'
True if file is a regular File.
`-g file'
True if file has its set-group-id bit set.
`-G file'
True if file is owned by the current effective group id.
`-k file'
True if file has its "sticky" bit set.
`-h file'
`-L file'
True if file is a symbolic Link.
`-O file'
True if file is owned by the current effective user id.
`-p file'
True if file is a named Pipe.
`-r file'
True if file is readable.
`-S file'
True if file is a Socket.
`-s file'
True if file has a Size greater than zero.
`-t [FD]'
True if FD is opened on a terminal. If FD is omitted, it defaults
to 1 (standard output).
`-u file'
True if file has its set-user-id bit set.
`-w file'
True if file is writable.
`-x file'
True if file is executable.
`file1 -ef file2'
True if file1 and file2 have the same device and inode numbers,
i.e., if they are hard links to each other.
File Age
These options test the file modification date.
`file1 -nt file2'
True if file1 is newer than file2.
`file1 -ot file2'
True if file1 is older than file2.
String tests
These options test string characteristics. Strings are not quoted for `test', though you may need to quote them to protect characters with special meaning to the shell, e.g., spaces.
`-z String'
True if the length of String is zero.
`-n String'
`String'
True if the length of String is nonzero.
`String1 = String2'
True if the strings are equal.
`String1 != String2'
True if the strings are not equal.
Numeric tests
Numeric relationals. The arguments must be entirely numeric (possibly negative), or the special expression `-l STRING', which evaluates to the length of STRING.
`ARG1 -eq ARG2'
`ARG1 -ne ARG2'
`ARG1 -lt ARG2'
`ARG1 -le ARG2'
`ARG1 -gt ARG2'
`ARG1 -ge ARG2'
These arithmetic binary operators return true if ARG1 is equal,
not-equal, less-than, less-than-or-equal, greater-than, or
greater-than-or-equal than ARG2, respectively.
For example:
test -1 -gt -2 && echo yes
=> yes
test -l abc -gt 1 && echo yes
=> yes
test 0x100 -eq 1
error--> test: integer expression expected before -eq
Examples
$ ls -al
total 67
drwxr-xr-x 18 root root 4096 Jun 9 21:12 ./
drwxr-xr-x 18 root root 4096 Jun 9 21:12 ../
-rw-rw-rw- 1 simon users 4096 Jun 9 07:30 london
-rwsrwsrwx 1 simon users 4096 Jun 9 07:32 aberdeen
-rw------- 1 simon users 4096 Jun 9 07:29 bristol
-rw-r--r-- 1 simon users 4096 Jun 9 07:29 bath
$
$ test -r paris
$ echo $?
1
$
Because the file `paris' is not Readable, the value returned is false (non zero)
if [ "$LOGNAME" = "scott" ]
then
echo "Logged in as Scott"
else
echo "incorrect user"
fi
If the logname variable = scott then the test returns TRUE (0)
"The test of a vocation is the love of the drudgery it involves" - Logan Pearsall
Related:
case - Conditionally perform a command
cmp - Compare two files
expr - Evaluate expressions
eval - Evaluate several commands/arguments
for - Expand words, and execute commands
if - Conditionally perform a command
pathchk - Check file name portability
Equivalent Windows command: IF - Conditionally perform a command
понедельник, 14 сентября 2009 г.
net-snmp-5.4.2.1 и переменная $PATH
На очередном сервере ставил snmpd из source. Делаю ./configure - всё пробежало норм. Даю make, вылезает ошибка:
make[5]: *** [libnetsnmp.la] Error 1
make[5]: Leaving directory
`../net-snmp/build/snmplib'
до этого на солярке той же версии всё ставилось норм. Начал рыть. Оказывается в переменной $PATH не было прописан путь /usr/ccs/bin/. Добавил в файл /etc/default/su. Ещё раз сконфигурил ./configure, дал make - пробежала :)
make[5]: *** [libnetsnmp.la] Error 1
make[5]: Leaving directory
`../net-snmp/build/snmplib'
до этого на солярке той же версии всё ставилось норм. Начал рыть. Оказывается в переменной $PATH не было прописан путь /usr/ccs/bin/. Добавил в файл /etc/default/su. Ещё раз сконфигурил ./configure, дал make - пробежала :)
пятница, 11 сентября 2009 г.
fork()
В Unix-системах, fork() — системный вызов, создающий новый (дочерний) процесс, идентичный выполняющему этот вызов. После вызова fork() алгоритм обычно разветвляется (родительский процесс получает от fork() PID дочернего, а дочерний получает нуль).
После fork() дочерний процесс чаще всего выполняет системный вызов exec(), загружающий в пространство процесса новую программу (именно так, и только так, в Unix-системе выполняется запуск программы в отдельном процессе). Так, первый (нулевой) процесс Unix (ядро системы) создаёт свою копию, чтобы запустить init (процесс с PID = 1), который в свою очередь создаёт дочерние процессы для запуска инициализации системы и терминалов.
Некоторые программы создают дочерние процессы не для запуска другой программы, а для выполнения параллельной задачи. Так, например, поступают простые сетевые серверы — при подсоединении клиента, сервер создаёт свою копию (дочерний процесс), которая обслуживает клиентское соединение и завершается по его закрытию. Родительский же процесс продолжает ожидать новых соединений.
Вызов fork() выполняется довольно долго, так как требует копирования большого количества данных. Для того чтобы это обойти, некоторые сетевые серверы (например, веб-серверы Apache и Lighttpd), создают дочерние процессы заранее, чтобы уменьшить время отклика сервера. Также существуют «облегченные» реализации fork(), отображающие в новый процесс страницы памяти родительского, вместо того чтобы их копировать (новая страница создаётся только при изменении её содержимого одним из процессов), что существенно снижает время создания нового процесса (т. н. copy-on-write).
После fork() дочерний процесс чаще всего выполняет системный вызов exec(), загружающий в пространство процесса новую программу (именно так, и только так, в Unix-системе выполняется запуск программы в отдельном процессе). Так, первый (нулевой) процесс Unix (ядро системы) создаёт свою копию, чтобы запустить init (процесс с PID = 1), который в свою очередь создаёт дочерние процессы для запуска инициализации системы и терминалов.
Некоторые программы создают дочерние процессы не для запуска другой программы, а для выполнения параллельной задачи. Так, например, поступают простые сетевые серверы — при подсоединении клиента, сервер создаёт свою копию (дочерний процесс), которая обслуживает клиентское соединение и завершается по его закрытию. Родительский же процесс продолжает ожидать новых соединений.
Вызов fork() выполняется довольно долго, так как требует копирования большого количества данных. Для того чтобы это обойти, некоторые сетевые серверы (например, веб-серверы Apache и Lighttpd), создают дочерние процессы заранее, чтобы уменьшить время отклика сервера. Также существуют «облегченные» реализации fork(), отображающие в новый процесс страницы памяти родительского, вместо того чтобы их копировать (новая страница создаётся только при изменении её содержимого одним из процессов), что существенно снижает время создания нового процесса (т. н. copy-on-write).
Подписаться на:
Сообщения (Atom)