1.通过进程的名字获得进程的ID
[root@dou proc]# ps -ef | grep sshd | grep -v grep
root 1078 3075 0 16:57 ? 00:00:00 sshd: root@pts/0
root 3075 1 0 03:35 ? 00:00:00 /usr/sbin/sshd
[root@dou proc]# pgrep sshd
1078
3075
2.修改bash提示符:
首先将现在的进行备份:
echo $PS1 >ps1.txt
然后在命令行设置如下一条命令:
PS1="[\e[1;31m\u\e[1;37m@\e[1;32m\h \e[1;33m\W\e[0m]\$"
3.bash中整数计算:
[root@dou bash]#a=$[2+3];echo $a
5
[root@dou bash]#a=$((3+4));echo $a
7
[root@dou bash]#a=`expr 4 + 5`;echo $a
9
[root@dou bash]#let a+=1;echo $a
1
4.bash中使用bc计算:
①修改小数位数
[root@dou etc]#echo "scale=2;2/100"|bc
.02
②修改进制
[root@dou etc]#echo "obase=2;100"|bc
1100100
[root@dou etc]#echo "obase=8;100"|bc
144
③计算平方根和幂
[root@dou bash]#echo "2^3" | bc
8
[root@dou bash]#echo "sqrt(100)" | bc
10
5.bash中自定义文件描述符
exec 3
cat <&3:读取文件描述符3中的内容
示例:
[root@dou bash]#echo "Hello World" > input.txt
[root@dou bash]#exec 3
[root@dou bash]#cat <&3
Hello World
exec 3<&-:关闭文件描述符3
示例:
[root@dou bash]#exec 3<&-
[root@dou bash]#cat <&3
-bash: 3: Bad file descriptor
exec 4>output.txt:创建文件描述符4用于写内容。
echo something >&4:将内容写入output.txt文件。
示例:
[root@dou bash]#exec 4>output.txt
[root@dou bash]#cat input.txt >&4
[root@dou bash]#cat output.txt
Hello World
exec 5>>input.txt:创建文件描述符5用于向文件input.txt追加内容。
示例:
[root@dou bash]#exec 5>>input.txt
[root@dou bash]#echo "Appending Hello World Again" >&5
[root@dou bash]#cat input.txt
Hello World
Appending Hello World Again
6.stty关闭输出
[root@dou bash]#cat stty.sh
#!/bin/bash
echo -n "Eneter password: "
stty -echo
read password
stty echo
echo
echo Password read.
7.定义一个函数
function functionname {
statements
}
bash中调用函数的时候世界使用函数名字即可。
示例:
[root@dou bash]#cat function.sh
#!/bin/bash
function hello {
echo "Hello World"
}
hello
[root@dou bash]#sh function.sh
Hello World
递归函数:
[root@dou bash]#cat recursive.sh
#!/bin/bash
F() { echo "$1";F "Hello World";sleep 1;}
F
传说中的Fork bomb:
:(){:|:&};:
8.read命令
示例:
[root@dou bash]#cat read.sh
#!/bin/bash
read -n 3 var
echo $var
read -p "enter something: " var
echo "$var"
read -s var
echo $var
read -t 5 var
echo $var
read -d ":" var
echo $var
[root@dou bash]#sh read.sh
123123
enter something: abc
abc
five
abc:
abc:
abc:abc
9.for循环:
示例:
[root@dou bash]#for((i=0;i<5;i++));do echo $i;done
0
1
2
3
4
[root@dou bash]# a=hello
[root@dou bash]# for((i=0;i<${#a};i++));do echo ${a:$i:1};done
h
e
l
l
o
10.while循环:
示例:
[root@dou bash]#cat while.sh
#!/bin/bash
i=0;
while [ $i -lt 5 ];
do
echo hello
let i++
done
[root@dou bash]#sh while.sh
hello
hello
hello
hello
hello
11.if语句
示例:
[root@dou bash]#cat if.sh
#!/bin/bash
i=5;
if [ $i -lt 3 ]; then
echo $i;
elif [ $i -le 6 ]; then
echo $i;
else
echo "number i is greater than 6";
fi
file="/etc/passwd";
if [ -e $file ]; then
echo "File exists";
else
echo "No";
fi
[root@dou bash]#sh if.sh
5
File exists
12.将tap键变为^I:
示例:
[root@dou bash]#cat tap.sh
var=1
var=2
var=3
var=4
[root@dou bash]#cat -T tap.sh
var=1
^Ivar=2
^Ivar=3
^I^Ivar=4
13.记录终端操作并回放:
示例:
[root@dou bash]#script -t 2> timing.log -a output.session
Script started, file is output.session
[root@dou bash]#echo $HOSTNAME
dou.perl.gov
[root@dou bash]#echo $LOGNAME
root
[root@dou bash]#exit
exit
Script done, file is output.session
[root@dou bash]#scriptreplay timing.log output.session
[root@dou bash]#echo $HOSTNAME
dou.perl.gov
[root@dou bash]#echo $LOGNAME
root
[root@dou bash]#exit
exit
[root@dou bash]#
14:共享终端演示:
示例:
1)打开一个终端:
[root@dou bash]#mkfifo scriptfifo
2)另开一个终端到同一个目录下:
[root@dou bash]#cat scriptfifo
3)回到第一个终端:
[root@dou bash]#script -f scriptfifo
Script started, file is scriptfifo
[root@dou bash]#echo hello
hello
[root@dou bash]#echo test
test
[root@dou bash]#
4)终端2也会显示如下内容:
[root@dou bash]#echo hello
hello
[root@dou bash]#echo test
test
[root@dou bash]#
15.小脚本计算字符数:
示例:
[root@dou bash]#cat count.sh
#!/bin/bash
string="abcheaadcdsefesofwfsesfsfwdfcsd"
output=$(echo $string | sed 's/[^\n]/&\n/g' | sed '/^$/d' | sort | uniq -c | tr -d ' \n')
echo $output
[root@dou bash]#sh count.sh
3a1b3c4d4e6f1h1o6s2w
16.csplit基于文件内容对文件进行分割:
示例:
[root@dou bash]#cat server.log
SERVER-1
[connection] 192.168.0.1 success
[connection] 192.168.0.2 failed
[disconnect] 192.168.0.3 pending
[connection] 192.168.0.4 success
SERVER-2
[connection] 192.168.0.1 failed
[connection] 192.168.0.2 failed
[disconnect] 192.168.0.3 success
[connection] 192.168.0.4 failed
SERVER-3
[connection] 192.168.0.1 pending
[connection] 192.168.0.2 pending
[disconnect] 192.168.0.3 pending
[connection] 192.168.0.4 failed
[root@dou bash]#csplit server.log /SERVER/ -n 2 -s {*} -f server -b "%02d.log"
[root@dou bash]#cat server01.log
SERVER-1
[connection] 192.168.0.1 success
[connection] 192.168.0.2 failed
[disconnect] 192.168.0.3 pending
[connection] 192.168.0.4 success
[root@dou bash]#cat server02.log
SERVER-2
[connection] 192.168.0.1 failed
[connection] 192.168.0.2 failed
[disconnect] 192.168.0.3 success
[connection] 192.168.0.4 failed
[root@dou bash]#cat server03.log
SERVER-3
[connection] 192.168.0.1 pending
[connection] 192.168.0.2 pending
[disconnect] 192.168.0.3 pending
[connection] 192.168.0.4 failed
17.计算文件中单词出现频率:
示例:
[root@dou bash]#cat input.txt
Hello World
Appending Hello World Again
[root@dou bash]#cat word_freq.sh
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 filename"
exit 1
fi
filename=$1
egrep -o "\b[[:alpha:]]+\b" $filename | awk '{count[$0]++}END{printf("%-14s%s\n","Word","Count");for(ind in count){printf("%-14s%d\n",ind,count[ind]);}}'
[root@dou bash]#sh word_freq.sh input.txt
Word Count
Appending 1
Hello 2
Again 1
World 2
18.Awk语法:
awk 'BEGIN{print "start"} pattern {commands} END{print "end"}' filename
[root@dou bash]#echo | awk '{var1=1;var2=2;print var1,var2}'
1 2
[root@dou bash]#echo | awk '{var1=1;var2=2;print var1":"var2}'
1:2
NR:行号
NF:字段数
$0:当前行的内容
$1,$2...:第一个、第二个字段的值...
从外面向awk传递变量值:
[root@dou bash]#echo | awk -v hostname=$HOSTNAME '{print hostname}'
dou.perl.gov
19.Awk模仿tail
示例:
[root@dou bash]# cat input.txt
Hello World
Appending Hello World Again
line 3
hello dou
[root@dou bash]# awk '{tail[NR%2] = $0;}END{for(i=1;i<3;i++){print tail[i%2]}}' input.txt
line 3
hello dou
20.Wget克隆网站:
wget --mirror
wget -r -N -l DEPTH
-l:指定了下载网页的深度。
但是如果网站有robots文件,那么该方法不行。
访问需要HTTP/FTP验证的网页
wget --user username --password pass
21.curl下载:
--silent:静默不将内容输出到stdout
--process:显示下载进度
curl -C - url:自动续传
curl -I/--head url:提取HTTP头部信息而不下载网页。
curl只打印访问网站的返回值:
[root@web-db bash]# curl -w %{http_code} -so /dev/null
200[root@web-db bash]#
22.生成网站缩略图:
示例:
[root@dou bash]# cat album.sh
#!/bin/bash
echo "Creating album..."
mkdir -p thumbs
cat <index.html
body
{
width:470px;
margin:auto;
border: 1px dashed grey;
padding:10px;
}
img
{ margin:5px;
border: 1px solid black;
}
#Album title
EOF
for img in *.jpg
do
convert "$img" -resize "100x" "thumbs/$img"
echo "" >> index.html done
cat <> index.html
EOF
echo Album generated to index.html
23.检测网站坏连接:
示例:
[root@dou bash]# cat tmp/find_broken.sh
#!/bin/bash
if [ $# -eq 2 ]; then
echo "Usage: $0 URL"
exit 1;
fi
echo Broken links:
mkdir /tmp/$$.lynx
cd /tmp/$$.lynx
lynx -traversal $1 > /dev/null
count=0
sort -u reject.dat > links.txt
while read link
do
output=$(curl -I $link -s | grep "HTTP/.*OK")
if [[ -z "$output" ]]; then
echo $link
let count++
fi
done < links.txt
[ $count -eq 0 ] && echo No broken links found.
但是经过测试,该脚本不怎么好用,对百度无可奈何。
24.使用curl与diff追踪网站变化:
示例:
[root@dou bash]# cat trackweb.sh
#!/bin/bash
first_time=0
if [ ! -e "last.html" ]; then
first_time=1
fi
curl --silent $1 -o recent.html
if [ $first_time -ne 1 ]; then
changes=$(diff -u last.html recent.html)
if [ -n "$changes" ]; then
echo "Changes:"
echo "$changes"
else
echo "Website has no changes"
fi
else
echo "[First run] Archiving..."
fi
mv recent.html last.html
25.curl的post请求练习
示例:
[root@dou bash]# curl \
> mlogs/submit.php -d "host=doudou&user=redhat"
You have entered :
26.使用squashfs文件:
示例:
安装需要的rpm包
[root@dou bash]# yum -y install squashfs-tools.x86_64
创建squashfs文件
[root@dou bash]# mksquashfs bash/ bash.squashfs
挂在squashfs文件到/mnt/squash目录
[root@dou bash]# mount -t squashfs -o loop bash.squashfs /mnt/squash/
创建squashfs文件时排除不需要包含的文件
[root@dou bash]# mksquashfs . 1.squashfs -e *.tar.*
上面的指令排除了当前目录下的*.tar.*文件
排除不需要的文件时也可以使用一个文件列表:
mksquashfs . 1.squashfs -ef excludelist(包含需要排除的文件名)
27.openssl产生/etc/shadow文件样式的shadow密码:
[root@dou bash]# openssl passwd -1 -salt hello 123456
$1$hello$ZwmhCpcG.I1XIfVjdarKc1
28.使用rsync进行备份:
如果源目录后面附加了"/"的话,不管目的目录后面有没有附加"/",都只会将目录中的内容拷贝到目的目录。
如果源目录后面没有附加了"/"的话,不管目的目录后面有没有附加"/",都会将源目录一同拷贝到目标目录中。
示例:
[root@dou bash]# ls backup/
[root@dou bash]# rsync -a expect5.45 backup
[root@dou bash]# ls backup/expect5.45/
aclocal.m4 expect_cf.h.in exp_memmove.c exp_trap.c Makefile.in
ChangeLog expect_comm.h exp_noevent.c exp_tstamp.h NEWS
[root@dou bash]# ls backup/
[root@dou bash]# rsync -a expect5.45/ backup/
[root@dou bash]# ls backup/
aclocal.m4 expect_cf.h.in exp_memmove.c exp_trap.c Makefile.in
ChangeLog expect_comm.h exp_noevent.c exp_tstamp.h NEWS
通过网络进行拷贝:
rsync -a source_dir username@host:PATH
rsync -a username@host:PATH destination_path
使用rsync的压缩功能:
rsync -az soure_path destination_path
排除不需要的文件:
--exclude pattern
示例:
[root@dou bash]# ls backup/
[root@dou bash]# ls expect5.45
aclocal.m4 expect_cf.h.in exp_memmove.c exp_trap.c Makefile.in
ChangeLog expect_comm.h exp_noevent.c exp_tstamp.h NEWS
config.log expect.h exp_poll.c exp_tty.c pty_sgttyb.c
configure expect.man exp_prog.h exp_tty_comm.c pty_termios.c
configure.in expect_tcl.h exp_pty.c exp_tty.h pty_unicos.c
Dbg.c exp_event.c exp_pty.h exp_tty_in.h README
example exp_event.h exp_regexp.c exp_win.c retoglob.c
exp_chan.c exp_glob.c exp_regexp.h exp_win.h tclconfig
exp_clib.c exp_inter.c exp_rename.h FAQ tcldbg.h
exp_closetcl.c exp_int.h exp_select.c fixline1 tests
exp_command.c exp_log.c exp_simple.c HISTORY testsuite
exp_command.h exp_log.h exp_strf.c INSTALL vgrindefs
exp_console.c exp_main_exp.c expTcl.c libexpect.man
expect.c exp_main_sub.c expTcl.h license.terms
[root@dou bash]# rsync -az expect5.45/ backup --exclude "*.[c|h]"
[root@dou bash]# ls backup/
aclocal.m4 configure expect_cf.h.in fixline1 libexpect.man NEWS tests
ChangeLog configure.in expect.man HISTORY license.terms README testsuite
config.log example FAQ INSTALL Makefile.in tclconfig vgrindefs
[root@dou bash]#
或者可以指定一个文件,然后使用--exclude-from选项:
删除源目的不存在而存在与目的地的文件:
rsync -az source_path destination_path --delete
使用cron job周期性调度rsync备份文件:
crontab -e
* * * * * rsync -az sourece_path destination_path
29.显示系统中的网络接口:
示例:
[root@dou bash]# ifconfig | cut -c-10 | tr -d ' ' | tr -s '\n'
eth0
eth1
lo
[root@dou bash]# ifconfig | grep '^[^ \t]'| awk '{print $1}'
eth0
eth1
lo
打印接口及对应的ip及netmask:
示例:
#!/bin/bash
for inter in `ifconfig | grep '^[^ \t]'| awk '{print $1}'`
do
ipaddr=`ifconfig $inter | egrep -o "addr:[^ ]*" | grep -o -P "[\d|.]+"`
netmask=`ifconfig $inter | egrep -o "Mask:[^ ]*" | grep -o -P "[\d|.]+"`
echo -e "Interface: $inter\nIpAddr: $ipaddr\nNetmask: $netmask\n";
done
#!/bin/bash
for inter in `ifconfig | grep '^[^ \t]'| awk '{print $1}'`
do
ifconfig $inter | egrep -o "((inet addr|Mask):[^ ]*|$inter)"
echo
done
30.修改接口的MAC地址:
示例:
[root@dou bash]# ifconfig eth0 | head -n 1
eth0 Link encap:Ethernet HWaddr 00:0C:29:19:FF:E3
[root@dou bash]# ifconfig eth0 hw ether 00:0C:29:19:FF:E8
[root@dou bash]# ifconfig eth0 | head -n 1
eth0 Link encap:Ethernet HWaddr 00:0C:29:19:FF:E8
31.捕捉ip对应的MAC地址:
示例:
arping -c 1 192.168.1.106|awk -F"[][]" '{print $2}'|sed '/^$/d'
32.修改系统默认的TTL值:
示例:
[root@dou bash]# echo 66 > /proc/sys/net/ipv4/ip_default_ttl
[root@dou bash]# ping -c 1 localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=66 time=0.021 ms
--- localhost.localdomain ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.021/0.021/0.021/0.000 ms
上述方法重启后无效,可以通过编辑配置文件/etc/sysctl.conf
添加:
net.ipv4.ip_default_ttl = 67
或者命令行:
[root@dou bash]# sysctl -w net.ipv4.ip_default_ttl=67
net.ipv4.ip_default_ttl = 67
[root@dou bash]# ping -c 1 localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=67 time=0.029 ms
--- localhost.localdomain ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.029/0.029/0.029/0.000 ms
[root@dou bash]# sysctl -a | grep net.ipv4.ip_default_ttl
net.ipv4.ip_default_ttl = 67
重启有效
33.检测网络主机存活状态:
示例:
[root@dou bash]# cat ping.sh
#!/bin/bash
for ip in 192.168.1.{1..255}
do
(
ping $ip -c 2 &> /dev/null
if [ $? -eq 0 ]; then
echo "$ip is alive"
fi
)&
done
wait # Let the script wait for the time until all the child()subshell processes complete.
34.fping并发检测主机存活状态:
fping -a 192.168.1.0/24 -g -C 1 -q
fping -a
fping -a -d 2>/dev/null
[root@dou bash]# fping 192.168.1.0/24 -g -C 1 2>/dev/null
192.168.1.1 : [0], 84 bytes, 1.99 ms (1.99 avg, 0% loss)
192.168.1.100 : [0], 84 bytes, 4.40 ms (4.40 avg, 0% loss)
192.168.1.103 : [0], 84 bytes, 2.56 ms (2.56 avg, 0% loss)
192.168.1.102 : [0], 84 bytes, 95.7 ms (95.7 avg, 0% loss)
192.168.1.107 : [0], 84 bytes, 0.07 ms (0.07 avg, 0% loss)
192.168.1.101 : [0], 84 bytes, 224 ms (224 avg, 0% loss)
35.自动ftp登陆上传下载文件:
示例:
[doudou@dou tmp]$ ls ~/
test
[doudou@dou tmp]$ ls
env.pl gconfd-root mapping-root MyHello-0.01
ftp.sh gnome-system-monitor.root.2672955347 MyDate-0.01 test1
[doudou@dou tmp]$ cat ftp.sh
#!/bin/bash
host="192.168.0.6"
user="doudou"
password="redhat"
ftp_command="/usr/bin/ftp"
$ftp_command -i -n $host <
user $user $password
binary
put test1
get test
quit
EOF
[doudou@dou tmp]$ sh ftp.sh
[doudou@dou tmp]$ ls ~/
test test1
[doudou@dou tmp]$ ls
env.pl gconfd-root mapping-root MyHello-0.01 test1
ftp.sh gnome-system-monitor.root.2672955347 MyDate-0.01 test
[doudou@dou tmp]$
36.通过ssh免密码登陆检测各服务器运行时间:
示例:
[root@dou bash]# cat uptime.sh
#!/bin/bash
ip="192.168.0.6"
user="root"
for ip in $ip
do
utime=$(ssh $user@$ip uptime | awk '{print $3}')
echo "$ip uptime: $utime"
done
37.ssh与数据压缩:
ssh -C user@hostname COMMANDS
38.将标准输入的内容重定向到运行在远程主机的shell命令中
echo "hello world" | ssh user@hostname 'cat >> list'
ssh user@hostname 'cat >> list' < file
39.使用zenity显示窗口信息:
示例:
[root@dou ~]# export DISPLAY=:0
[root@dou ~]# zenity --info --text "this is a message"
[root@dou ~]#
40.显示系统所有开放的端口以及相对应的服务:
示例:
[root@dou bash]# lsof -i
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
dhclient 2422 root 4u IPv4 6763 UDP *:bootpc
portmap 2640 rpc 3u IPv4 7189 UDP *:sunrpc
portmap 2640 rpc 4u IPv4 7190 TCP *:sunrpc (LISTEN)
rpc.statd 2677 root 3u IPv4 7323 UDP *:736
rpc.statd 2677 root 6u IPv4 7309 UDP *:733
41.查看文件占用空间大小:
示例:
[root@dou bash]# du -sh ../bash
40M ../bash
查找占用磁盘空间前10的文件和目录:
[root@dou bash]# du -ak .|sort -nrk 1 | head -n 11 | tail
12964 ./xz-5.0.4
8260 ./xz-5.0.4/src
6860 ./bash-4.2.tar.gz
6380 ./xz-5.0.4/src/liblzma
4472 ./1.squashfs
4420 ./tcl8.5.13-src.tar.gz
3456 ./lynx-cur.tgz
2856 ./xz-5.0.4/src/liblzma/.libs
2744 ./expect5.45
1344 ./util-linux-2.12r.tar.bz2
过滤目录,只要文件:
[root@dou bash]# find . -type f -exec du -k {} \; | sort -nrk 1 |head
6860 ./bash-4.2.tar.gz
4472 ./1.squashfs
4420 ./tcl8.5.13-src.tar.gz
3456 ./lynx-cur.tgz
2936 ./big file
1344 ./util-linux-2.12r.tar.bz2
1256 ./xz-5.0.4.tar.gz
1084 ./xz 5.0.4/src/liblzma/.libs/liblzma.a
788 ./bash
620 ./expect5.45.tar.gz
42.查看rpm安装时间:
查看rpm包的安装时间
rpm -qi rpm_name
或者如果通过yum安装的话请查看
less /var/log/yum.log
43:访问bash位置变量中的$#位置变量:
[root@web-db masterbash]# cat para.sh
#!/bin/bash
echo "$(eval echo "\$$#")"
echo "${!#}"
a=$(eval echo '$'$#)
echo $a
[root@web-db masterbash]# sh para.sh 1 3 5 7
7
7
7
[root@web-db masterbash]#
44.here-document and here-string:
here-string:将变量的内容作为命令的标准输入。
[root@web-db masterbash]# while read line;do
> echo $line
> done <
> hello world one
> hello world two
> hello world three
> end
> EOF
hello world one
hello world two
hello world three
end
[root@web-db masterbash]#
[root@web-db masterbash]# string="hello world good"
[root@web-db masterbash]# echo $string
hello world good
[root@web-db masterbash]# grep good <<<"$string"
hello world good
[root@web-db masterbash]# grep yes <<<"$string"
[root@web-db masterbash]#
45:process substitute
[root@web-db masterbash]# while read hostname
> do
> echo $hostname
> done < <(hostname)
web-db.example.com
[root@web-db masterbash]# while read hostname; do echo $hostname; done < <(date)
Sat Dec 22 16:00:00 CST 2012
[root@web-db masterbash]# while read hostname; do echo $hostname; done <<(date)
-bash: syntax error near unexpected token `('
[root@web-db masterbash]# while read hostname; do echo $hostname; done < <(echo $PATH)
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@web-db masterbash]#
阅读(269) | 评论(0) | 转发(0) |