shell技巧

来源:互联网 发布:指尖兼职淘宝是真的吗 编辑:程序博客网 时间:2024/05/01 15:16
1.bash中用什么命令可以从文件中读取固定的一行?
程序代码 程序代码
sed -n 5p file

2.press any to continue...的实现
程序代码 程序代码

...
echo -n "Press any to continue ..."
read
....

程序代码 程序代码

echo -n "Press any key to continue..."
read -n 1 foo

3.用stty和dd实现暂停,只须按一个键就可.
程序代码 程序代码

#!/bin/ksh
#
function char {
settty=$(stty -g)
stty raw
dd if=/dev/tty bs=1 count=1 2> /dev/null
stty -raw
stty $settty
}
print "Press any key to continue..."
input=$(char)

4.如何检查用户的输入?
程序代码 程序代码

#!/bin/ksh
#要求用户必须输入四个数字
while true
do
echo -n "请输入四个数字:"
read num
len=${#num}
#变量len存放输入的长度
if [[ $num != [0-9][0-9][0-9][0-9] || $len != 4 ]] then
#进行检测,如果你输入有非数字字符,或者长度不等于四个,便提示错误信息
echo "错误! 重新输入"
continue
else
echo "输入正确,退出!";exit 0
fi
done

5.把输入的密码变成*号的方法
程序代码 程序代码

#!/bin/sh
getchar() {
stty cbreak -echo
dd if=/dev/tty bs=1 count=1 2> /dev/null
stty -cbreak echo
}
printf "Please input your passwd: "
while : ; do
ret=`getchar`
if [ -z $ret ]; then
echo
break
fi
str="$str$ret"
printf "*"
done
echo "Your password is: $str"

5.在BASH下简单实现十进制到二进制和十六进制的转换
程序代码 程序代码

#!/bin/bash
#scriptname:conver
#在BASH下简单实现十进制到二进制和十六进制的转换
cat<<info
1] 10=>2 2] 10=>16
info
read input?"please enter your choice:"
case $input in
1) echo -n "please a dec number:";read i1
echo "$i1==$(echo "obase=2;$i1"|bc)" ;;
2) echo -n "please a dec number:";read i2
echo "$i2==$(echo "obase=16;$i2"|bc)" ;;
*) echo "wrong choice!"
exit 1 ;;
esac

7.统计文本中单词数量的方法
$cat kshfile
ksh
The "Korn" shell, written by David Korn of AT&T Bell Labs (now Lucent). Written as a major upgrade to "sh", it is compatible with it, but has many more internal commands for the most frequently used functions. It also incorporates most of the same features from tcsh which enhance interactive use (command line history recall etc.). This shell is now available on most systems. It was slow
to gain acceptance because earlier versions were encumbered by AT&T licensing.
程序代码 程序代码

$cat kshfile|tr " " "/n"|grep -wc shell

8.倒读文本
程序代码 程序代码

$cat -n tmp
1 abcdefgh
2 123234234
3 sjdfk23423
1,行号倒序:
$cat -n tmp|tac #tac和cat很有趣吧~~
3 sjdfk23423
2 123234234
1 abcdefgh
2,每行倒读:
$cat tmp|rev
hgfedcba
432432321
32432kfdjs
3,全部倒过来:
$cat -n tmp|rev|tac
32432kfdjs 3
432432321 2
hgfedcba 1
4,用sed也可以解决要求对sed有足够的理解)
$cat -n tmp|sed '//n/!G;s//(./)/(.*/n/)/&/2/1/;//D;s/.//'
hgfedcba 1
432432321 2
32432kfdjs 3

9.把汉字转换成十六进制和二进制的方法
程序代码 程序代码

$ echo '中国' | od -h
0000000 d0d6 fab9 000a
0000005


10.bash脚本调试
程序代码 程序代码

bash -x 脚本名


11.sed输出一例
程序代码 程序代码

cat domaina.txt |sed 's//|/ /g'

 http://www.cmuch.com/trackback.asp?tbID=96
原创粉丝点击