【发布时间】:2013-11-27 01:07:27
【问题描述】:
我需要编写一个带有一个或多个参数(文件名)的 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' -
您需要在字符串周围添加一些 " 或 ' 以避免出现空格问题。
标签: linux bash shell terminal sh