如何将文件作为参数传递给脚本文件

时间:2010-10-19 21:54:34

标签: shell unix

我有一个用bash编写的shell脚本,这个脚本应该以文件为参数,任何人都可以告诉我如何编写脚本,对此有任何想法都很赞赏

谢谢,

2 个答案:

答案 0 :(得分:2)

您可以使用positional parameters访问传递给脚本的命令行参数。

另外,要检查是否已将正确数量的参数传递给脚本,您可以使用包含传递的参数数量的变量$#

if [ $# -eq 1 ]; then
        # exactly 1 argument was passed..use it..its available in $1
        echo "Argument $1"
else
        # either 0 or >1 arguments were passed...error out.
        echo "Incorrect number of arguments passed"
        exit 1             
fi

示例运行:

$ bash a.sh
Incorrect number of arguments passed
$ bash a.sh foo
Argument foo
$ bash a.sh foo bar
Incorrect number of arguments passed
$ 

答案 1 :(得分:0)

如果您需要对文件进行操作,可以将文件名作为参数,并使用具有指定名称的文件。

如果您只需要阅读文件的内容,则可以使用重定向让脚本在标准中读取文件的内容。您可以使用./script < inputfile

执行此操作