在终端中执行rm -rf !(*.txt),成功删除.txt以外的文件,但是把这句放在脚本中,会报错。
LOCATION=/export/home/byang/Test
if [ -d  $Location ]; then
  cd $Location
  LD_LIBRARY_PATH=/usr/local/lib
  export LD_LIBRARY_PATH
  ls *.zip > a.asc
if test -s a.asc; then
   cat a.asc | while read line
   do
        echo $line
        cd $LOCATION
        7za e $line -y
  done
fi
cd $LOCATION
pwd
sleep 10
rm -rf !(*.txt)
rm *Summary.txtfi
报错信息为:
$ ./test.sh
./test.sh: line 19: syntax error near unexpected token `!(*'
./test.sh: line 19: `rm -rf !(*.txt)'
不懂为什么会报错?要怎么修改?

解决方案 »

  1.   

    试试第一行加上 #!/bin/bash 或者 #!/bin/sh 等。
      

  2.   

    第一行是有#!/bin/bash的,我只是没有写到这里。
      

  3.   

    rm -rf !(*.txt)中的括号是个特殊符号,因此会报错。替代语句是rm -rf `find . ! -name "*.txt"`.感谢大神。
      

  4.   

    rm -rf !(*.txt)   在交互式shell下面 ! 表示历史记录扩展功能,语法没有错。在脚本默认关闭了历史记录扩展功能,所以语法报错。
    如果怀疑我说的!的功能,请 man bash 看一下就知道了。
      

  5.   

    https://linux.die.net/man/1/bash
    History Expansion 部分The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. This feature is enabled by default for interactive shells, and can be disabled using the +H option to the set builtin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default.
    内容太多,后面省略,请查看链接