外壳脚本中的算术(字符串中的算术)



我正在尝试编写一个简单的脚本,该脚本创建由循环中的变量枚举的五个文本文件。谁能告诉我如何计算算术表达式。这似乎不起作用:

touch ~/test$(($i+1)).txt

(我知道我可以在单独的语句或循环更改中评估表达式......

提前感谢!

正确答案取决于您使用的 shell。 它看起来有点像bash,但我不想做太多假设。

您列出的命令touch ~/test$(($i+1)).txt将使用任何$i+1正确接触文件,但它没有执行的是更改$i的值。

在我看来,你想做的是:

  • 在名为testn.txt的文件中查找 n 的最大值,其中 n 是大于 0 的数字
  • 数字递增为 m。
  • 触摸(或以其他方式输出(名为testm.txt的新文件,其中 m 是递增的数字。

使用此处列出的技术,您可以去除文件名的各个部分以构建所需的值。

假设以下内容位于名为"touchup.sh"的文件中:

#!/bin/bash
# first param is the basename of the file (e.g. "~/test")
# second param is the extension of the file (e.g. ".txt")
# assume the files are named so that we can locate via $1*$2 (test*.txt)
largest=0
for candidate in (ls $1*$2); do
intermed=${candidate#$1*}
final=${intermed%%$2}
# don't want to assume that the files are in any specific order by ls
if [[ $final -gt $largest ]]; then
largest=$final
fi
done
# Now, increment and output.
largest=$(($largest+1))
touch $1$largest$2