linux - Bash 中的脚本参数

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

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

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

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

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

最佳答案

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

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

./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 可能更容易,例如:

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

那么你将拥有:

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

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

那么你可以这样做:

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

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

https://stackoverflow.com/questions/18003370/

相关文章:

python - "hashable"在 Python 中是什么意思?

python - numpy 矩阵向量乘法

python - 在python中跳过for循环的第一个条目?

python - 如何在 Python 中将方法作为参数传递

linux - Linux Bash 中的双与号 (&&) 和分号 (;) 有什么区别?

python - 如何将整数时间戳转换为日期时间

python - 如何从一列中对 Pandas 数据框进行排序

asp.net - 在基于 Linux 的服务器上运行 ASP.Net

linux - 如何获取 Linux/UNIX 上当前的网络接口(interface)吞吐量统计信息

python - pip 安装 : Please check the permissions and