如果执行脚本时出现syntax错误,如 line 9: syntax error: unexpected end of file 并且提示出错的行比脚本中最后一行的数字还大时,检查脚本中的行尾是否有空格,删除行尾空格就应该能解决这类错误。在vim中使用 :% s/\s*$//即可删除行尾的空白字符,包括<Space> 和 <Tab>。
2009-02-10
shell脚本中的行尾空格引起的错误
2007-06-29
用${}过滤变量
${}用于过滤变量的值有时候非常方便,不过每次用都记不住,只好写个例子在此供翻查:(提醒一下,别与命令替换操作符 $(command) 搞混了!另外在XSLT中可以用{$var}来得到一个变量的值)
假设 FNAME="/home/jia/tmp/test.1.sh"
那么有:
${FNAME}
显示变量的全部。
/home/jia/tmp/test.1.sh
${FNAME##/*/}
比对变量開端﹐如果以 /*/ 开头的話﹐砍掉最長的部份。
test.1.sh
${FNAME#/*/}
比对变量开端﹐如果以 /*/ 开头的話﹐砍掉最短的部份。
jia/tmp/test.1.sh
${FNAME%.*}
比对变量末端﹐如果以 .* 結尾﹐砍掉最短的部份。
/home/jia/tmp/test.1
${FNAME%%.*}
比对变量末端﹐如果以 .* 結尾﹐砍掉最长的部份。
/home/jia/tmp/test
${FNAME/sh/bash}
如果在变量中找到 sh ﹐將第一个 sh 替换为 bash。
/home/jia/tmp/test.1.bash
${FNAME//sh/bash}
如果在变量中找到 sh ﹐將全部 sh 替换为 bash。
/home/jia/tmp/test.1.bash
简单总结:
# 比对变量的的开始部分
% 比对变量的结束部分
一个符号表示去掉最短的部分,两个符号表示去掉最长的部分。
2006-06-23
2005-03-17
2005-03-10
grep+find的使用
以前在一个目录下查找某个字符串总是搭配find+grep来使用,如:
写个简单脚本mygrep.sh包括下面内容find $1 -type f -exec grep -s $2 {} ; -print
要查找muster时,执行 mygrep.sh . "muster" 即可。
2005-03-05
如何删除一个目录下除了某一个文件的大量文件
在linux下如何删除一个目录下除了某些文件的大量文件:
解决办法:
删除除了一个文件之外的所有文件: ls !(file) | xargs rm
删除除了几个文件之外的所有文件:
ls !(file1|file2|...|fileN) | xargs rm
2004-08-11
$@等特定shell变量的含义
在shell脚本的实际编写中,有一些特殊的变量十分有用:
$# 传递到脚本的参数个数
$* 以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此参数可超过9个
$$ 脚本运行的当前进程ID号
$! 后台运行的最后一个进程的进程ID号
$@ 与$#相同,但是使用时加引号,并在引号中返回每个参数
$- 显示shell使用的当前选项,与set命令功能相同
$? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。
2004-08-07
2004-07-31
2004-07-21
2004-06-20
2004-06-19
display the longest filename, given a directory as argument
Code:
#!/bin/bash
#Revision Number 1.1
#Pass directory as first argument ($1)
#Initialization
maxlen=0
#Check for directory argument
if [ $# -ne 1 ]; then
echo "Usage: len.sh [directory]"
exit
fi
#Obtain list of filenames for directory and store it in namelist
ls -lpR $1 | grep -v / | tr -s " " | cut -d" " -f9 > namelist
#Find longest name
for file in `cat namelist`; do
len=${#file}
if [ $len -gt $maxlen ]; then
((maxlen=len))
maxfilename=$file
fi
done
#Display it
echo "Longest filename in $1 is $maxfilename with length=$maxlen"
#Remove temporary file
rm -f namelist