Shell Notes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Print absolute path of the script.
function abs_path() {
python -c "import os.path; print(os.path.realpath('$0'))";
}

# get absolute path of the current script
ABS_PATH=`abs_path`

# get path of directory
$(dirname $ABS_PATH)

# get filename
$(basename $ABS_PATH)

# Download the tar file specified by arg1, extract to arg2 (the
# top-level folder will be stripped) and remove the downloaded
# file.
# e.g. download_and_extract_to \
# http://releases.llvm.org/3.6.0/cfe-3.6.0.src.tar.xz \
# llvm/tools/clang
# @arg1 download_url
# @arg2 extract_to_folder
function download_and_extract_to() {
URL=$1
FOLDER=$2

FILENAME=$(basename $URL)

wget $URL
mkdir -p $FOLDER
tar --strip 1 -xf $FILENAME -C $FOLDER
rm $FILENAME
}

# empty a file
: > file.txt
truncate -s0 file.txt

# build file index for current directory
find $(pwd) -type f > filelist.txt

# copy a part of a file
dd count=<copy_N_ibs_sized_blocks> skip==<copy_N_ibs_sized_blocks> \
if=<input_file> of=<output_file>
# add iflag=count_bytes,skip_bytes to copy and skip in bytes
# instead of blocks
dd iflag=count_bytes,skip_bytes count=<copy_bytes> skip=<skip_bytes> \
if=<input_file> of=<output_file>

# search for keyword in some specific types of files
find . -type f -name "*.java" -print0 |xargs -0 grep -li "keyword"

# -n1 is used to execute the command once for each result
find . -type f -name "*.java" -print0 |xargs -0 -n1 echo

# The -I option to xargs takes a string that will be
# replaced with the supplied input before the command
# is executed. A common choice is %.
find /path -type f -name '*~' -print0 | xargs -0 -I % cp -a % ~/backups

# The word bash at the end of the line is interpreted by bash
# -c as special parameter $0.
# The single quote ' is critical, otherwise $filename will be
# replaced before the script is executed.
find /path -type f -name '*~' -print0 | xargs -0 bash -c \
'for filename; do cp -a "$filename" ~/backups; done' bash