在bash脚本参数 [英] Script parameters in Bash

查看:88
本文介绍了在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

但我不知道怎么弄的 - 从 -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 其中的数字指的是参数。 $ 1,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.

的参数用空格分隔,所以如果你在命令中提供 - 从 -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

您会得到:

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

这可能是更容易忽略 - 从 -to ,如:

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 并不总是必要的,但被劝,因为一些字符串赢得了双引号如果你不把它们放在双引号之间的科技工作。

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天全站免登陆