日期:2014-05-16  浏览次数:20705 次

在linux下将脚本设置为可执行
我有一个脚本文件 命名为first
#!/bin/sh

#first
#This file looks through all the files in the current
#directory for the string POSIX,and then prints the names of
#those files to the standard output.

for file in *
do
  if grep -q POSIX $file
  then
    echo $file
  fi
done

exit 0

该文件保存在/home/henry/目录下,用pwd命令显示出当前所在目录为/home/henry/
我想在shell中运行这个脚本。
如果直接输入:$. first    ——就能直接运行成功
如果输入 :$chmod +x first 
          $./first        ——这样显示无法找到文件
想知道第二种方法为什么不行?

------解决方案--------------------
引用:
Quote: 引用:

不是脚本没有被执行.而是grep说没有找到One这个文件或者目录.
建议调试查看下file这个变量怎么会出现One这个值.
ls -la 查看当前目录到底有哪些文件/文件夹.
脚本 加一句 set -x 调试看看.
#!/bin/sh
set -x
#first
#This file looks through all the files in the current
#directory for the string POSIX,and then prints the names of
#those files to the standard output.
 
for file in *
do
  echo "找到文件:" $file
  if grep  -q POSIX $file
  then
    echo $file
  fi
done


本人刚学shell编程,脚本程序是照书上抄的。。调试还看不出来原理。


找到了 ,可爱的grep/shell没有识别出带有空格的文件名,
就是你上面的Ubuntu One被认为是两个文件(夹): Ubuntu 和 One .
只要在原来的文件中修改:

```
if grep  -q POSIX $file   #$file加对引号,变为下面的样子
if grep  -q POSIX "$file"
```

我这双引号测试ok了.具体双引号还是单引号还是一个坑,得慢慢啃呢.

------解决方案--------------------
#!/bin/sh

#first
#This file looks through all the files in the current
#directory for the string POSIX,and then prints the names of
#those files to the standard output.

for file in *; do
    if grep -q POSIX "$file"; then
        echo "$file"
    fi
done

exit 0