我想写接受任何数目的打印出rwx
权限的文件(不是目录)命令行参数的微小脚本
什么我是
[email protected]
if [ -f $file ] ; then
ls -l $file
fi
但是,只接受一个命令行参数。谢谢你的帮助。
我想写接受任何数目的打印出rwx
权限的文件(不是目录)命令行参数的微小脚本
什么我是
[email protected]
if [ -f $file ] ; then
ls -l $file
fi
但是,只接受一个命令行参数。谢谢你的帮助。
传递给脚本的所有参数的bash变量是“$ *”。尝试:
for file in $*; do
if [ -f $file ] ; then
ls -l $file
fi
done
(未测试)
这不适用于包含空格的参数。请始终使用“$ @”代替,并引用所有变量。 – Philipp 2009-10-16 09:08:52
,你可以有效地遍历像这样指定的任何文件:
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
这件怎么样:
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“
为了清楚起见,我认为通常最好包括'$ @'。 – Cascabel 2009-10-15 21:42:02
这是一个品味问题,但我同意你的看法。很长一段时间我一直在包括$ @,但最近刚刚停止这样做。 – 2009-10-16 04:55:43
你想要的变量确实是[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]"
这里的一些$*
和[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..
我很好奇,这似乎与其他一些问题密切相关 - 谨慎给予更多背景? – 2009-10-15 22:44:48