[英]Analyzing Files in a Shell Script
我需要编写一个包含一个或多个参数(文件名)的shell脚本。 无论文件名是否包含空格,都应正确处理。 对于每个文件,脚本应检查文件是否可读,可写,可执行,是否是纯文件以及是否是目录。 对于这些检查中的每一项,都应将Y或N放置在适当的列中。 如果文件不存在,则在每个字段中都应加上破折号“ ---”。
Example output:
Read Write Execute Plain Dir Filename
Y Y Y Y N /tmp/testfiles/executable
Y Y N Y N /tmp/testfiles/file with spaces
Y N N Y N /tmp/testfiles/justread
N Y N Y N /tmp/testfiles/justwrite
N N N Y N /tmp/testfiles/noperms
--- --- --- --- --- /tmp/testfiles/nosuchfile
Y Y N Y N /tmp/testfiles/readwrite
Y Y Y N Y /tmp/testfiles/somedir
我对UNIX shell脚本不是很熟悉,但是在在线阅读了各种文章之后,我想到了以下解决方案。
#! /bin/sh
echo Read Write Execute Plain Dir Filename
argnum=0
while $argnum < $# do
FileExists $($argnum)
PrintFileName $($argnum)
done
function FileExists()
{
if test -e $1
then
IsReadable $1
IsWritable $1
IsExecutable $1
IsPlain $1
IsDir $1
else
echo --- --- --- --- ---
}
function IsReadable()
{
if test -r $1
then
echo Y
else
echo N
}
function IsWritable()
{
if test -w $1
then
echo Y
else
echo N
}
function IsExecutable()
{
if test -x $1
then
echo Y
else
echo N
}
function IsPlain()
{
if test -f $1
then
echo Y
else
echo N
}
function IsDirectory()
{
if test -d $($argnum)
then
echo Y
else
echo N
}
function PrintFilename()
{
echo $1
}
不幸的是,脚本无法正确执行。 我知道有问题(尤其是格式问题),但是我不确定如何解决它们。 您的任何帮助/建议都将不胜感激。
读写执行普通Dir文件名./script:第7行:意外标记附近的语法错误已完成'./script:7行:已完成
这是因为,您需要一个;
在do
之前。
Bash从上到下扫描,并执行每一行。 因此,在前几行中,Bash不了解FileExists
和PrintFileName
。 因此,您需要做的是在调用声明之前放置声明。
function FileExists
{
...
}
function IsReadable
{
...
}
// more functions..
//Iterate here and call the above functions.
更干净的迭代方式:
for var in "$@"
do
FileExists $var
PrintFileName $var
done
您可能会遇到格式问题,因为echo会换行。 而且您可能无法一things而就。 请改用printf
,然后手动写出printf "\\n"
。
另外,@ devnull指出,在if
块的每个单个实例中都缺少fi
。
尽管“ function Name()”语法有效,但我更喜欢declare -f Name
返回的样式作为我的书面形式,因为我使用“ declare -f name ...”来重现函数主体。
同样,您可以从每个函数中考虑“回声Y”和“回声N”,只需返回断言的真相即可。 因此,... IsReadable,..变成:
IsReadable ()
{
test -r $1
}
并使用
IsReadable $1 && echo Y || echo N
因为我找不到“ &&”(与)和“ ||” (OR)语法太吵。 另外,我更喜欢这个
[[ -r $1 ]] && echo Y || echo N
所以,我是isreadable
:
isreadable () { [[ test -r $1 ]] ; }
因为我允许“ declare -f”规则的单行例外,甚至还有一个函数, fbdy
可以做到这一点:如果函数主体(较少的标头,尾部)适合一行,则将其显示为单行,否则,将其显示为默认值。
很高兴看到您使用函数。 保持。 我大力鼓励使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.