Shell脚本文件测试

时间:2015-11-08 03:23:48

标签: bash shell command-line-arguments

我必须执行以下步骤:

一个。接受文件名作为命令行参数

湾检查足够数量的命令行参数。

℃。检查给定文件是否存在。

d。检查文件是否可读。

即使用语句exit 0

成功退出程序

这是我到目前为止所做的,但是当我运行脚本时,我总是得到“无效参数”和“文件不存在”作为输出。

#! /bin/bash
filename=$1

if [ $# -eq 1 ]
    then
    echo $1
else
    echo "Invalid argument"
fi

if [ -e "$1" ]; then
    echo "File Exists"
    exit 1
else
    echo "File Does not Exist"
    exit 1
fi

if [ -r "$1" ]; then
    echo "File is readable"
    exit 1
else
    echo "File is not readable"
    exit 1
fi

1 个答案:

答案 0 :(得分:1)

好的 - 所以,你输入bash myfilename.sh。这意味着您正在运行脚本但未向myfilename.sh传递任何参数。请尝试以下方法:

echo "This is a test file" > testfile.dat

这将创建一个名为testfile.dat的文件,其中包含一些文本。 (文件中的实际文本并不重要。如果你有时间,你可以输入莎士比亚的全部作品。但它不会改变你的shell脚本的功能)。接下来,将脚本作为

运行
bash myfilename.sh testfile.dat

或只是

myfilename.sh testfile.dat

在这里,您要告诉您的脚本检查是否存在testfile.dat

祝你好运。

相关问题