我正在编写一个脚本,如果我在终端中调用参数,它将允许我将字符串中的字符从“#”更改为其他字符。
例如,如果我写
./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/