Bash - 如何执行语法:./ myscript.sh * .dat?

时间:2012-07-16 21:27:00

标签: bash

我想以递归方式运行myscript.sh,以执行目录中的所有文件:

我已经讨论过here我可以这样做:

#!/bin/bash

for file in * ; do
    echo $file
done

但我希望myscript.sh能够使用这种语法执行,这样我就只能选择某些文件类型来执行:

./ myscript.sh * .dat

因此我修改了上面的脚本:

#!/bin/bash

for file in $1 ; do
    echo $file
done

在执行时,它只执行第一次出现,而不是所有带有* .dat扩展名的文件。

这里有什么问题?

3 个答案:

答案 0 :(得分:6)

在脚本看到之前, shell 扩展了通配符*.dat。因此,文件名在您的脚本中显示为$1$2$3等。

您可以使用特殊的$@变量

一次性使用它们
for file in "$@"; do
    echo $file
done

请注意"$@"周围的双引号是特殊的。来自man bash

@  Expands to the positional parameters, starting from one.  When  the  expansion
   occurs  within double quotes, each parameter expands to a separate word.  That
   is, "$@" is equivalent to "$1" "$2" ...  If the double-quoted expansion occurs
   within  a word, the expansion of the first parameter is joined with the begin-
   ning part of the original word, and the expansion of  the  last  parameter  is
   joined  with the last part of the original word.  When there are no positional
   parameters, "$@" and $@ expand to nothing (i.e., they are removed).

答案 1 :(得分:-2)

你可以用ls *.dat | xargs echo

做同样的事情

答案 2 :(得分:-2)

您需要获取*的实际内容,如下所示:

for file in $* ; do
 echo $file 
done