我正在尝试编写一个简单的脚本,该脚本创建一个循环中的变量枚举的五个文本文件。谁能告诉我如何对算术表达式求值。这似乎不起作用:
touch ~/test$(($i+1)).txt
((我知道我可以在单独的语句中评估表达式或更改循环...)
提前感谢!
正确的答案取决于您使用的外壳。它看起来有点像bash,但我不想做太多假设。
您列出的touch ~/test$(($i+1)).txt
命令将正确地使用$i+1
来触摸文件,但它没有执行的操作是更改$i
的值。
我想你想做的是:
testn.txt
的文件中找到n的最大值,其中n是大于0的数字testm.txt
的新文件,其中m是递增的数字。使用列出的技术here,您可以剥离文件名的各个部分以构建所需的值。
假设以下内容位于名为“ 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