求教:为什么cat 老是出错?

sh/bash/dash/ksh/zsh等Shell脚本
回复
xxxxusky
帖子: 12
注册时间: 2006-09-24 19:20

求教:为什么cat 老是出错?

#1

帖子 xxxxusky » 2006-12-12 22:55

#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
  cat <
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
  exit 0
}
# in case of error or if -h is given we call the function help:
[ -z "$1" ] && help
[ "$1" = "-h" ] && help
# send the escape sequence to change the xterm titelbar:
echo -e "33]0;$107"
#

以上程序是精华区里面的东西,但是我运行出现了如下错误
./xtitlebar: line 5: syntax error near unexpected token `newline'
./xtitlebar: line 5: `  cat <'

其实我就是看不懂这个cat
输出多断文字不是用here documnets么,权威文字如下:

当要将几行文字传递给一个命令时,here documents(译者注:目前还没有见到过对该词适合的翻译)一种不错的方法。对每个脚本写一段帮助性的文字是很有用的,此时如果我们四有那个 here documents就不必用echo函数一行行输出。 一个 "Here document" 以 << 开头,后面接上一个字符串,这个字符串还必须出现在here document的末尾。下面是一个例子,在该例子中,我们对多个文件进行重命名,并且使用here documents打印帮助:
#!/bin/sh
# we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ] ; then
cat <
ren -- renames a number of files using sed regular expressions
USAGE: ren 'regexp' 'replacement' files...
EXAMPLE: rename all *.HTM files in *.html:
 ren 'HTM$' 'html' *.HTM
HELP
 exit 0
fi
OLD="$1"
NEW="$2"
# The shift command removes one argument from the list of
# command line arguments.
shift
shift
# $* contains now all the files:
for file in $*; do
  if [ -f "$file" ] ; then
   newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`
   if [ -f "$newfile" ]; then
    echo "ERROR: $newfile exists already"
   else
    echo "renaming $file to $newfile ..."
    mv "$file" "$newfile"
   fi
  fi
done

但是在这个程序里here documents在哪?
我尝试自己使用heredocuments
写一个测试的
#!/bin/sh
help()
{
cat <<emo
This is the usage of here documents!
second line
emo
}
help()
有如下错误:
./test: line 10: syntax error: unexpected end of file

高手帮忙阿
严重打击我学习shell的动力阿
呜呜
头像
千里孤坟
帖子: 212
注册时间: 2005-12-08 16:53
联系:

#2

帖子 千里孤坟 » 2006-12-15 10:08

精华区那个代码和“权威说明”之后的示例代码中Here Document声明都是有遗漏的,楼主没注意到吗?

就精华区这个例子来说,把

代码: 全选

cat < 
改成

代码: 全选

cat << HELP 
就可以了。

关于楼主自己写的示例,Shell里执行自定义函数不要加括号,所以把最后一行的括号去掉便好。
xxxxusky
帖子: 12
注册时间: 2006-09-24 19:20

#3

帖子 xxxxusky » 2006-12-15 10:27

thx
回复