开发者

how to pass file as an argument to the script file

开发者 https://www.devze.com 2023-01-21 14:30 出处:网络
I have a shell script written in bash and this script should take file as an argument,can any one tell me how to wri开发者_运维知识库te script for this any ideas on this are apprecited

I have a shell script written in bash and this script should take file as an argument,can any one tell me how to wri开发者_运维知识库te script for this any ideas on this are apprecited

Thanks,


You can access the command line arguments passed to your script using positional parameters.

Also to check if the right number of arguments have been passed to the script, you can make use of the variable $# which holds the number of arguments passed.

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

Sample run:

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


If you need to operate on the file, you can take the name of the file as an argument and just use the file with the specified name.

If you just need to read the contents of the file, you can use redirection to have the script read the contents of the file on standard in. You can do this using ./script < inputfile

0

精彩评论

暂无评论...
验证码 换一张
取 消