linux - Bash编程如何调用 "$i+1"

标签 linux string bash terminal increment

我正在编写一个脚本,如果我在终端中调用参数,它将允许我将字符串中的字符从“#”更改为其他字符。

例如,如果我写

 ./myprogram testText.txt -r a

-r 参数将从 testTxt.txt 中删除所有“#”并用“a”替换它们

我的问题是我不知道如何写“如果 -r 是 $x,$x+1 是我想要替换的字符”

这纯粹是语法问题,我是 bash 菜鸟 :P。这是我尝试使用的代码部分。

 for i in $*
 do
     if [[ $i = "-r" ]]
     then
          $customHashChoice=$((i+1))
             # ^^^^^ Problematic Line ^^^^
        fi
 done

最佳答案

试试这个:

customHashChoice=($(getopt "r:" "$@" 2>/dev/null))
if [ "${customHashChoice[0]}" == "-r" ]; then
    customHashChoice="${customHashChoice[1]}"
else
    echo "-r option is missing. Aborting..."
    exit 1
fi

语法:getopt optstring 参数

来自手册:getopt 用于分解(解析)命令行中的选项以便 shell 程序轻松解析,并检查合法选项。它使用 GNU getopt(3) 例程来执行此操作。

在这里,optstring 是r:。这意味着,脚本接受一个选项 -r 并且该选项接受一个参数(由 : 隐含)。

getopt "r:""$@" 的输出如下:

-r <argument to -r option> -- <unmatched parameters>

例如对于命令行参数,

 ./myprogram testText.txt -r a

getopt "r:""$@" 返回

 -r a -- testText.txt

此输出存储在数组中,如果第一个元素等于 -r,则使用数组的第二个元素。

关于linux - Bash编程如何调用 "$i+1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23285415/

相关文章:

c++ - 如何显示 256x256 的网格?

Java - 设置首选项后备存储目录

string - perl 使用正则表达式拆分字符串,但将分隔符连接到输出

linux - 合并排序的文件,缓冲最少

regex - 存在多个/不完整匹配项时 'grep -w -f"的行为

bash - 我怎样才能在 bash 中找到 "try to do something and then detect if it fails"?

c - C 是否使用 try&catch 来保证核心转储不会崩溃?

linux - 如何在 linux 的 tomcat7 webapps 中复制我的 war 文件

c - 如何使用C将两个整数组合成一个字符串?

python - 通过python从响应数据中检索特定数据