1. Since bash 3.2, regex should always be unquoted.
use a variable to store your regex, e.g. re='^\*( >| *Applying |.*\.diff|.*\.patch)'; [[ $var =~ $re ]]
2. Whenever you're making a Bash script, you should always use [[ rather than [.
3. Should better use $(...) instead of `...` for command substitution
4. Learn to use parameter expansions instead of sed or cut to manipulate simple strings in Bash. If you want to remove the extension from a filename, use ${filename%.*} instead of`echo "$filename" | sed 's/\.[^.]*$//'` or some other dinosaur.
1. get the exit status in the pipeline command
use PIPESTATUS array(bash only)
eg:
grep foo somelogfile | head -5
status=${PIPESTATUS[0]}
2. read ----- 不是一行行的读,而是以null(\0)作为delimier
while read -r -d $'\0'
-r -------- prevent it from treating backslash as special usage
3. find xxxx -print0 | xargs -0 command {}
note:The find command itself uses the -print0 option as mentioned before to tell it to separate the filenames it finds with a NUL byte instead of a newline.
also it tells xargs, instead of reading whitespace-separated words, to read NUL-delimited words instead
{} means the output
find xxxx -exec commands {} \;
find xxxx -exec commands {} +
note: the + (instead of ;) at the end of the -exec action tells find to use an internal xargs-like feature which causes the commands to be invoked only once for every chunk of files, instead of once per file.
4. print the nth line of a file
sed -n "${n}p" "$file"
#But above command reads the entire file even if only the third line is desired, which can be avoided by printing line $n using the p command, followed by a q to exit the script.
sed -n "$n{p;q;}" "$file"
5. glob pattern
-
*: Matches any string, including the null string.
-
?: Matches any single character.
-
[...]: Matches any one of the enclosed characters.
note: When a glob is used to match filenames, the * and ? characters cannot match a slash (/) character. So, for instance, the glob */bin might match foo/bin but it cannot match /usr/local/bin. When globs match patterns, the / restriction is removed
`command` or $(command)
7. command group
$ grep -q goodword "$file" && ! grep -q badword "$file" && { rm "$file" || echo "Couldn't delete: $file" >&2; }
(Note: don't forget that you need a semicolon or newline before the closing curly brace!)
8. process substitution
<() ---- the result as other's input
>() ---- others as the process's input
not use process substitution
$ head -n 1 .dictionary > file1
$ tail -n 1 .dictionary > file2
$ diff -y file1 file2
Aachen | zymurgy
$ rm file1 file2
use process substitution
$ diff -y <(head -n 1 .dictionary) <(tail -n 1 .dictionary)
Aachen | zymurgy
9. sourcing a script
$ . ./myscript
note: do above in a script means run the "myscript" in current shell environment not in a subshell environment
10. using getopts to parse command options