星期四, 6月 28, 2007

shell script備忘記

# 依最後更改時間 刪除檔案
find ./yourpath -type -f -mtime -beforeDays -exec rm -f {} \;

# ftp script
#!/usr/bin/sh
fm_year="`date +%Y'`"
fm_monday="`date +'%m%d'`"
fm_dir_prefix="/db/db_backup"
fm_dir="${fm_dir_prefix}/${fm_year}/${fm_monday}"
ftp -i -n 192.168.1.1 <<FTPIT
user dbuser dbpass
bin
cd $fm_dir
lcd dump
mget *.*
quit
FTPIT

sort 指令
將讀入的檔案作排序.
-f 把英文字母當成大寫來看
-n 將各行前頭的數字來做排序
-r 將排序順序逆轉
-b 將欄位前的空格省略
-u 去除重複行
-o 將輸出導入至檔案
[-t seperator] seperator為分隔符 ex. sort -t, -k2, 3 filename
-k pos1[,pos2] pos1為以第一個position作排序
sort +1n filename (跳過每行第一段落作排序)



uniq 指令
-d 將重複行顯示出來
-u 將不重複行顯示出來
-c 統計出現的次數


cut 指令
[-d seperator] seperator為分隔符
-f field field為指定輸出的欄位 ex. cut -d : -f2,4-6


awk -F: '{ print $5 }' (顯示seperator為":"的第5行)
awk -F: '{ print $1 ":" $5 }' (顯示seperator為":"的第1及5行)


paste 指令
[-d seperator] seperator為分隔符 ex. paste -d = file1 file2 file3


diff 指令
-y 將兩個檔案 side-by-side 輸出
[-W cols] cols為指定顯示的寬度 ex. diff -y -W90 file1 file2


wc 指令
-l 統計行數
-c 統計單詞數
-w 統計字數


expand -4 將縮排轉換成4空格


unexpand 指令 將行頭的空格轉換成縮排
unexpand -a filename 將所有空格轉換成縮排


read -r filename 逐行讀入檔案
IFS=$'\n' # IFS 系統預設的區隔符 這裡為換行
ln=0
while read -r line; do
ln=`expr $ln + 1`
printf '%3d %s\n' "$ln" "$line"
done < "$1"



split -b 1m infile outfile
將輸入檔案分割成指定大小


tr e x < filename (將檔案裡的 e 字符轉換成 x 字符)
tr '[a-z]' '[A-Z]' < filename (將小寫轉成大寫)
tr -s ' ' ' ' < filename (-s為將連結一樣的轉成一個)
tr -d ' ' < filename (-d為刪除所有空格)


sed 's/from/to/G' filename (將檔案裡的 from 轉換成 to)
sed -n '1,2p' filename (將檔案的1至2行輸出)
sed -n '/seachKey/p' filename (將檔案含有 seachKey 的行輸出)
sed '1,2d' filename (刪除第1,2行)
sed '/seachKey/d' filename (刪除含有 seachKey 的行)


Array:
message=(hi there how are you today)
message[0]=hi
message[1]=there
message[2]=how
message[3]=are
message[4]=you
message[5]=today


names=([2]=alice [0]=hatter [1]=duchess)


names=(hatter duchess alice)


names=(hatter [5]=duchess alice)


for i in "${names[@]}"; do
echo $i
done


for i in $(cut -f 1,3 -d: /etc/passwd) ; do
array[${i#*:}]=${i%:*}
done


values=(39 5 36 12 9 3 2 30 4 18 22 1 28 25)
numvalues=${#values[@]}
for (( i=0; i < numvalues; i++ )); do
echo -ne "${values[$i]}\t"
done


if/else:
String comparison operators:
str1 = str2[4]
str1 matches str2

str1 != str2
str1 does not match str2

str1 < str2
str1 is less than str2

str1 > str2
str1 is greater than str2

-n str1
str1 is not null (has length greater than 0)

-z str1
str1 is null (has length 0)



if [ -z $filename ]; then
echo "File not found"
exit 1
fi


File attribute operators:
-a file
file exists

-d file
file exists and is a directory

-e file
file exists; same as -a

-f file
file exists and is a regular file (i.e., not a directory or other special type of file)

-r file
You have read permission on file

-s file
file exists and is not empty

-w file
You have write permission on file

-x file
You have execute permission on file, or directory search permission if it is a directory

-N file
file was modified since it was last read

-O file
You own file

-G file
file's group ID matches yours (or one of yours, if you are in multiple groups)

file1 -nt file2
file1 is newer than file2 [6]

file1 -ot file2
file1 is older than file2

Arithmetic test operators:
-lt
Less than

-le
Less than or equal

-eq
Equal

-ge
Greater than or equal

-gt
Greater than

-ne
Not equal

for:

for x := 1 to 10 do
begin
statements...
end


IFS=:
for dir in $PATH
do
ls -ld $dir
done


case:
for filename in "$@"; do
case $filename in
*.jpg ) exit 0 ;;
*.gif ) exit 0 ;;
* ) exit 1 ;;
esac
done


while/until:
while [ $path ]; do
ls -ld ${path%%:*}
path=${path#*:}
done


until cp $1 $2; do
echo 'Attempt to copy failed. waiting...'
sleep 5
done


while test $# -gt 0
do
case $1 in
done


Function:
process( ) {
cat "$1"
}


for f in "$@"
do
process "$f"
done



: (colon) Do nothing (just do expansions of arguments).


. (dot) Read file and execute its contents in current shell.


alias Set up shorthand for command or command line (interactive use).


bg Put job in background (interactive use).


break Exit from surrounding for, while, or until loop.


cat Copy input to output


cd Change working directory.


command Locate built-in and external commands; find a built-in command instead of an


identically named function.

continue Skip to next iteration of for, while, or until loop.


cut Extract columns from input

eval Process arguments as a command line.

exec Replace shell with given program or change I/O for shell.

exit Exit from shell.

export Create environment variables.

false Do nothing, unsuccessfully.

fc Work with command history (interactive use).

fg Put background job in foreground (interactive use).

getopts Process command-line options.

grep Search for strings in the input


jobs List background jobs (interactive use).

kill Send signals.

newgrp Start new shell with new group ID (obsolete).

pwd Print working directory.

read Read a line from standard input.

readonly Make variables read-only (unassignable).

return Return from surrounding function.


sed Perform editing operations on input

set Set options or positional parameters.

shift Shift command-line arguments.

sort Sort lines in the input


times Print accumulated user and system CPU times for the shell and its children.


tr Translate characters in the input to other characters

trap Set up signal-catching routine.

true Do nothing, successfully.

umask Set/show file permission mask.

unalias Remove alias definitions (interactive use).

unset Remove definitions of variables or functions.

wait Wait for background job(s) to finish.



$# Number of command-line arguments.


$- Options currently in effect (arguments supplied on command line or to set). The shell


sets some options automatically.


$? Exit value of last executed command.


$$ Process number of current process.


$! Process number of last background command.


$0 First word; that is, the command name. This will have the full pathname if it was found


via a PATH search.


$n Individual arguments on command line (positional parameters). The Bourne shell allows


only nine parameters to be referenced directly (n = 1–9); Bash allows n to be greater than


9 if specified as ${n}.


$*, $@ All arguments on command line ($1 $2 ...).


"$*" All arguments on command line as one string ("$1 $2..."). The values are separated by


the first character in IFS.


"$@" All arguments on command line, individually quoted ("$1" "$2" ...).


VI command:
h Move left one character

l Move right one character

w Move right one word

b Move left one word

W Move to beginning of next non-blank word

B Move to beginning of preceding non-blank word

e Move to end of current word

E Move to end of current non-blank word

0 Move to beginning of line

^ Move to first non-blank character in line

$ Move to end of line

i Text inserted before current character (insert)

a Text inserted after current character (append)

I Text inserted at beginning of line

A Text inserted at end of line

R Text overwrites existing text

dh Delete one character backwards

dl Delete one character forwards

db Delete one word backwards

dw Delete one word forwards

dB Delete one non-blank word backwards

dW Delete one non-blank word forwards

d$ Delete to end of line

d0 Delete to beginning of line

D Equivalent to d$ (delete to end of line)

dd Equivalent to 0d$ (delete entire line)

C Equivalent to c$ (delete to end of line, enter input mode)

cc Equivalent to 0c$ (delete entire line, enter input mode)

X Equivalent to dl (delete character backwards)

x Equivalent to dh (delete character forwards)

k or - Move backward one line

j or + Move forward one line

G Move to line given by repeat count

/string Search backward for string

?string Search forward for string

n Repeat search in same direction as previous

N Repeat search in opposite direction of previous

fx Move right to next occurrence of x

Fx Move left to previous occurrence of x

tx Move right to next occurrence of x, then back one space

Tx Move left to previous occurrence of x, then forward one space

; Redo last character-finding command

, Redo last character-finding command in opposite direction

~ Invert (twiddle) case of current character(s)

- Append last word of previous command, enter input mode

CTRL-L Clear the screen and redraw the current line on it; good for when your screen


becomes garbled

# Prepend # (comment character) to the line and send it to the history list; useful


for saving a command to be executed later without having to retype it[8]


set nu Display number of lines


History Expansion:
! Start a history substitution

!! Refers to the last command

!n Refers to command line n

!-n Refers to the current command line minus n

!string Refers to the most recent command starting with string

!?string? Refers to the most recent command containing string; the ending ? is optional

^string1^string2 Repeat the last command, replacing string1 with string2

Time stamp formats:
%a
The locale's abbreviated weekday name

%A
The locale's full weekday name

%b
The locale's abbreviated month name

%B
The locale's full month name

%c
The locale's appropriate date and time representation

%C
The century number (the year divided by 100 and truncated to an integer) as a decimal


number [00-99]

%d
The day of the month as a decimal number [01-31]

%D
The date in American format; the same value as %m/%d/%y.

%e
The day of the month as a decimal number [1-31]; a single digit is preceded by a space

%h
The same as %b

%H
The hour (24-hour clock) as a decimal number [00-23]

%I
The hour (12-hour clock) as a decimal number [01-12]

%j
The day of the year as a decimal number [001-366]

%m
The month as a decimal number [01-12]

%M
The minute as a decimal number [00-59]

%n
A newline character

%p
The locale's equivalent of either a.m. or p.m

%r
The time in a.m. and p.m. notation; in the POSIX locale this is equivalent to %I:%M:%S %p

%R
The time in 24-hour notation (%H:%M)

%S
The second as a decimal number [00-61]

%t
A tab character

%T
The time (%H:%M:%S)

%u
The weekday as a decimal number [1-7], with 1 representing Monday

%U
The week number of the year (Sunday as the first day of the week) as a decimal number [00-


53]

%V
The week number of the year (Monday as the first day of the week) as a decimal number [01-


53]; if the week containing 1 January has four or more days in the new year, then it is


considered week 1—otherwise, it is the last week of the previous year, and the next week is


week 1

%w
The weekday as a decimal number [0-6], with 0 representing Sunday

%W
The week number of the year (Monday as the first day of the week) as a decimal number [00-


53]; all days in a new year preceding the first Monday are considered to be in week 0

%x
The locale's appropriate date representation

%X
The locale's appropriate time representation

%y
The year without century as a decimal number [00-99]

%Y
The year with century as a decimal number

%Z
The timezone name or abbreviation, or by nothing if no timezone information exists

%%
%


I/O redirectors: ("$@" > logfile 2>&1 &)
cmd1 cmd2
Pipe; take standard output of cmd1 as standard input to cmd2.

> file
Direct standard output to file.

< file
Take standard input from file.

>> file
Direct standard output to file; append to file if it already exists.

> file
Force standard output to file even if noclobber is set.

n> file
Force output to file from file descriptor n even if noclobber is set.

<> file
Use file as both standard input and standard output.

n<> file
Use file as both input and output for file descriptor n.

<< label
Here-document; see text.

n> file
Direct file descriptor n to file.

n< file
Take file descriptor n from file.

n>> file
Direct file descriptor n to file; append to file if it already exists.

n>&
Duplicate standard output to file descriptor n.

n<&
Duplicate standard input from file descriptor n.

n>&m
File descriptor n is made to be a copy of the output file descriptor.

n<&m
File descriptor n is made to be a copy of the input file descriptor.

&>file
Directs standard output and standard error to file.

<&-
Close the standard input.

>&-
Close the standard output.

n>&-
Close the output from file descriptor n.

n<&-
Close the input from file descriptor n.

n>&word
If n is not specified, the standard output (file descriptor 1) is used. If the digits in


word do not specify a file descriptor open for output, a redirection error occurs. As a


special case, if n is omitted, and word does not expand to one or more digits, the standard


output and standard error are redirected as described previously.

n<&word
If word expands to one or more digits, the file descriptor denoted by n is made to be a


copy of that file descriptor. If the digits in word do not specify a file descriptor open


for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed.


If n is not specified, the standard input (file descriptor 0) is used.

n>&digit-
Moves the file descriptor digit to file descriptor n, or the standard output (file


descriptor 1) if n is not specified.

n<&digit-
Moves the file descriptor digit to file descriptor n, or the standard input (file


descriptor 0) if n is not specified. digit is closed after being duplicated to n.

echo escape sequences:
\a
ALERT or CTRL-G (bell)

\b
BACKSPACE or CTRL-H

\c
Omit final NEWLINE

\e
Escape character (same as \E)

\E
Escape character[3]

\f
FORMFEED or CTRL-L

\n
NEWLINE (not at end of command) or CTRL-J

\r
RETURN (ENTER) or CTRL-M

\t
TAB or CTRL-I

\v
VERTICAL TAB or CTRL-K

\n
ASCII character with octal (base-8) value n, where n is 1 to 3 digits

\0nnn
The eight-bit character whose value is the octal (base-8) value nnn where nnn is 1 to 3


digits

\xHH
The eight-bit character whose value is the hexadecimal (base-16) value HH (one or two


digits)

\\
Single backslash

printf format specifiers: (printf "hello %s\n" world)
%c
ASCII character (prints first character of corresponding argument)

%d
Decimal integer

%i
Same as %d

%e
Floating-point format ([-]d.precisione[+-]dd) (see following text for meaning of precision)

%E
Floating-point format ([-]d.precisionE[+-]dd)

%f
Floating-point format ([-]ddd.precision)

%g
%e or %f conversion, whichever is shorter, with trailing zeros removed

%G
%E or %f conversion, whichever is shortest, with trailing zeros removed

%o
Unsigned octal value

%s
String

%u
Unsigned decimal value

%x
Unsigned hexadecimal number; uses a-f for 10 to 15

%X
Unsigned hexadecimal number; uses A-F for 10 to 15

%%
Literal %

Meaning of precision:
%d, %I, %o, %u, %x, %X
The minimum number of digits to print. When the value has fewer digits, it is padded with


leading zeros. The default precision is 1.

%e, %E
The minimum number of digits to print. When the value has fewer digits, it is padded with


zeros after the decimal point. The default precision is 10. A precision of 0 inhibits


printing of the decimal point.

%f
The number of digits to the right of the decimal point.

%g, %G
The maximum number of significant digits.

%s
The maximum number of characters to print.

Flags for printf:
-
Left-justify the formatted value within the field.

space
Prefix positive values with a space and negative values with a minus.

+
Always prefix numeric values with a sign, even if the value is positive.

#
Use an alternate form: %o has a preceding 0; %x and %X are prefixed with 0x and 0X,


respectively; %e, %E and %f always have a decimal point in the result; and %g and %G do not


have trailing zeros removed.

0
Pad output with zeros, not spaces. This only happens when the field width is wider than the


converted result. In the C language, this flag applies to all output formats, even non-


numeric ones. For bash, it only applies to the numeric formats.



basename
The basename utility, missing from some systems


dirfuncs
Directory manipulation facilities


dirname
The dirname utility, missing from some systems


whatis
An implementation of the Tenth Edition Bourne shell whatis builtin


whence
An almost exact clone of the Korn shell whence builtin


沒有留言: