linux - 在 Shell 脚本中分析文件

标签 linux bash shell terminal sh

我需要编写一个带有一个或多个参数(文件名)的 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
}

不幸的是,脚本没有正确执行。我知道存在问题(尤其是格式方面),但我不确定如何解决这些问题。非常感谢您的任何帮助/建议。

最佳答案

Read Write Execute Plain Dir Filename ./script: line 7: syntax error near unexpected token done' ./script: line 7: done'

这是因为,在 do 之前需要一个 ;

Bash 从上到下扫描,并执行每一行。所以在前几行中,Bash 不知道 FileExistsPrintFileName。所以您需要做的是将声明放在之前调用它们。

function FileExists
{
...
}

function IsReadable
{
...
}
// more functions..

//Iterate here and call the above functions.

更简洁的迭代方式:

for var in "$@"
do
    FileExists $var
    PrintFileName $var
done

您可能在格式化时遇到问题,因为 echo 吐出一个换行符;而且您可能只是无法在一行中得到东西。使用 printf 代替,手动写出 printf "\n"

此外,@devnull 指出,if block 的每个实例中都缺少 fi

关于linux - 在 Shell 脚本中分析文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19970596/

相关文章:

linux - 如何计算文件在linux上执行的次数

linux - 在 Redhat Linux 上安装 Mercurial

c - 当我有 AF_UNIX 的 socket() 时,为什么我需要 socketpair()?

linux - 如果结果超过我的 shell 上的一个页面,如何自动传递到 less?

shell - 在 Cygwin 下编译 fish shell?

php - 设置一个新的 Cron 来运行 PHP 文件,但似乎没有任何反应

linux - 在一个巨大的文件中迭代很长的行

bash - 尝试在 cygwin 中运行脚本时出错

linux - 如何在没有后台进程的情况下并行运行 shell 命令?

linux - 如何监视 linux 二进制文件以测试 shell 脚本