Bash 中的脚本参数 [英] Script parameters in Bash

查看:34
本文介绍了Bash 中的脚本参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 shell 脚本,它应该像这样使用:

I'm trying to make a shell script which should be used like this:

ocrscript.sh -from /home/kristoffer/test.png -to /home/kristoffer/test.txt

然后脚本会将图像文件 ocr 转换为文本文件.到目前为止,这是我想出的:

The script will then ocr convert the image file to a text file. Here is what I have come up with so far:

#!/bin/bash
export HOME=/home/kristoffer
/usr/local/bin/abbyyocr9 -rl Swedish -if ???fromvalue??? -of ???tovalue??? 2>&1

但我不知道如何获取 -from-to 值.关于如何做到这一点的任何想法?

But I don't know how to get the -from and -to values. Any ideas on how to do it?

推荐答案

您提供给 bashscript 的参数将出现在变量 $1$2 中>$3 其中数字指的是参数.$0 是命令本身.

The arguments that you provide to a bashscript will appear in the variables $1 and $2 and $3 where the number refers to the argument. $0 is the command itself.

参数用空格分隔,所以如果你在命令中提供 -from-to,它们也会在这些变量中结束,所以对于这个:

The arguments are seperated by spaces, so if you would provide the -from and -to in the command, they will end up in these variables too, so for this:

./ocrscript.sh -from /home/kristoffer/test.png -to /home/kristoffer/test.txt

你会得到:

$0    # ocrscript.sh
$1    # -from
$2    # /home/kristoffer/test.png
$3    # -to
$4    # /home/kristoffer/test.txt

省略 -from-to 可能更容易,例如:

It might be easier to omit the -from and the -to, like:

ocrscript.sh /home/kristoffer/test.png /home/kristoffer/test.txt

然后您将拥有:

$1    # /home/kristoffer/test.png
$2    # /home/kristoffer/test.txt

缺点是您必须以正确的顺序提供它.有一些库可以更轻松地在命令行上解析命名参数,但通常对于简单的 shell 脚本,如果没有问题,您应该只使用简单的方法.

The downside is that you'll have to supply it in the right order. There are libraries that can make it easier to parse named arguments on the command line, but usually for simple shell scripts you should just use the easy way, if it's no problem.

然后你可以这样做:

/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1

$1$2 周围的双引号并不总是必需的,但建议使用,因为如果不将它们放在 double 之间,某些字符串将不起作用引用.

The double quotes around the $1 and the $2 are not always necessary but are adviced, because some strings won't work if you don't put them between double quotes.

这篇关于Bash 中的脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆