2009-10-15 239 views
3

我想写接受任何数目的打印出rwx权限的文件(不是目录)命令行参数的微小脚本

什么我是

[email protected]  
if [ -f $file ] ; then  
ls -l $file  
fi 

但是,只接受一个命令行参数。谢谢你的帮助。

+0

我很好奇,这似乎与其他一些问题密切相关 - 谨慎给予更多背景? – 2009-10-15 22:44:48

回答

0

传递给脚本的所有参数的bash变量是“$ *”。尝试:

for file in $*; do 
    if [ -f $file ] ; then 
    ls -l $file 
    fi 
done 

(未测试)

+0

这不适用于包含空格的参数。请始终使用“$ @”代替,并引用所有变量。 – Philipp 2009-10-16 09:08:52

1

,你可以有效地遍历像这样指定的任何文件:

for file in "[email protected]"; do 
    ls -l "$file" 
done 

如果你想仔细检查,确定指定的名称是一个目录,你可以这样做:

for file in "[email protected]"; do 
    if [ ! -d "$file" ]; then 
    ls -l "$file" 
    fi 
done 
+0

应引用'$ @'和'$ file'来保护空格和其他特殊字符。 – Cascabel 2009-10-15 21:41:15

+0

非常正确 - 我的思维太懒惰了。非常感谢。现在已修复。 :-) – Tim 2009-10-15 21:50:37

3

这件怎么样:

for file 
do 
    test -f "$file" && ls -l "$file" 
done 

for循环默认情况下会在$ @上工作,所以您不必提及它。请注意,如果文件名具有嵌入空间,则需要引用“$ file”。例如,如果你的脚本保存到“myll.sh”:

$ myll.sh "My Report.txt" file1 file2 

然后“我的REPORT.TXT”将被作为一个整体象征,而不是2个独立的令牌传递:“我”和“报告。 txt“

+1

为了清楚起见,我认为通常最好包括'$ @'。 – Cascabel 2009-10-15 21:42:02

+0

这是一个品味问题,但我同意你的看法。很长一段时间我一直在包括$ @,但最近刚刚停止这样做。 – 2009-10-16 04:55:43

2

你想要的变量确实是[email protected] - 它包含所有的命令行参数作为单独的单词,每个单词都完好无损(无扩展)。 ($*将它们全部作为一个单词 - 如果文件名中有空格,祝你好运)。

如果你喜欢,你可以循环。这很容易扩展到比ls更复杂的操作。

for file in "[email protected]"; do 
    if [ -f "$file" ]; then 
     ls -l "$file" 
    fi 
done 

注意:你应该引用[email protected]来保护里面的任何特殊字符!你也应该引用$file出于同样的原因 - 尤其是在测试中。如果[email protected]中有一个空字符串,则file也将为空,并且不带引号,-f将尝试对']'执行操作。错误随之而来。

另外,如果你需要做的是ls(跳过你if)你可以这样做:

ls -l "[email protected]" 
8

这里的一些$*[email protected]之间的差异的示范,有和无报价:

#/bin/bash 
for i in $*; do 
    echo "\$*: ..${i}.." 
done; echo 
for i in "$*"; do 
    echo "\"\$*\": ..${i}.." 
done; echo 
for i in [email protected]; do 
    echo "\[email protected]: ..${i}.." 
done; echo 
for i in "[email protected]"; do 
    echo "\"\[email protected]\": ..${i}.." 
done; echo 

运行它:

[email protected]$ ./paramtest abc "space here" 
$*: ..abc.. 
$*: ..space.. 
$*: ..here.. 

"$*": ..abc space here.. 

[email protected]: ..abc.. 
[email protected]: ..space.. 
[email protected]: ..here.. 

"[email protected]": ..abc.. 
"[email protected]": ..space here..