csh/sh for 循环 - 如何?
我正在尝试编写一个在 FreeBSD 上执行 2 个脚本的 for 循环。我不在乎它是用 sh 还是 csh 编写的。我想要这样的东西:
for($i=11; $i<=24; $i++)
{
exec(tar xzf 'myfile-1.0.' . $i);
// detect an error was returned by the script
if ('./patch.sh')
{
echo "Patching to $i failed\n";
}
}
请问有人知道该怎么做吗?
谢谢
i'm trying to write a for loop that executes 2 scripts on FreeBSD. I don't care if it's written in sh or csh. I want something like:
for($i=11; $i<=24; $i++)
{
exec(tar xzf 'myfile-1.0.' . $i);
// detect an error was returned by the script
if ('./patch.sh')
{
echo "Patching to $i failed\n";
}
}
Does anyone know how to do this please?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 sh 中执行此操作的典型方法是:
请注意,
seq
不是标准的。根据工具的可用性,您可以尝试:或者
或者
我做了一些更改: 如果 tar 失败并且不发出错误消息,我将中止,因为 tar 应该发出错误消息而不是脚本。
The typical way to do this in sh is:
Note that
seq
is not standard. Depending on the availability of tools, you might try:or
or
I've made a few changes: I abort if the tar fails and do not emit an error message, since tar should emit the error message instead of the script.
哇!没有 BASH。可能没有 Kornshell:
用纯 Bourne shell 编写,就像上帝的意图一样。
请注意,您必须使用
expr
命令将 1 添加到$i
。 Bourne shell 不做数学运算。反引号表示执行命令并将命令中的 STDOUT 放入$i
中。Kornshell 和 BASH 使这变得更加容易,因为它们可以进行数学计算并执行更复杂的 for 循环。
Wow! No BASH. And probably no Kornshell:
Written in pure Bourne shell just like God intended.
Note you have to use the
expr
command to add 1 to$i
. Bourne shell doesn't do math. The backticks mean to execute the command and put the STDOUT from the command into$i
.Kornshell and BASH make this much easier since they can do math and do more complex for loops.
csh 确实可以很好地循环,问题是您正在使用 exec,它将当前程序(即 shell)替换为另一个程序,在同一进程中。由于其他人提供了 sh 版本,这里是一个 csh 版本:
不确定
./patch.sh
您是否正在测试它的存在或运行它?我在这里运行它,并测试结果 - true 意味着它返回零。或者:csh does loops fine, the problem is that you are using exec, which replaces the current program (which is the shell) with a different one, in the same process. Since others have supplied sh versions, here is a csh one:
Not sure about the
./patch.sh
are you testing for its existence or running it? I am running it here, and testing the result - true means it returned zero. Alternatively:我认为你应该只使用 bash。我这里没有它,所以它无法测试它,但是应该可以工作:
编辑:只需阅读评论,发现 FreeBSD 默认安装中没有 bash。所以这可能根本不起作用 - 我不确定 (t)csh 和 bash 之间的区别。
I think you should just use bash. I don't have it here, so it cannot test it, but something along this should work:
EDIT: Just read the comments and found out there's no bash in FreeBSD default installation. So this might not work at all - I'm not sure about the differences between (t)csh and bash.
那么我刚刚所做的是以下内容。
加载 sh shell,然后 for 循环就像在 Linux 上一样工作。
Well what i just did is the following.
Load sh shell and then for loop works like on linux.