gpt4 book ai didi

linux - 在 Shell 脚本中分析文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:22 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com