Foreach循环不会运行

时间:2017-07-20 02:48:15

标签: linux shell

家庭作业是修改这个脚本以将exec作为参数,但首先我希望能够运行脚本以试图找出如何修改它

tcsh $ cat foreach_1
#!/bin/tcsh
# routine to zero-fill argv to 20 arguments
#

set buffer = (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
set count = 1
#
if ($#argv > 20) goto toomany
#
foreach argument ($argv[*])
set buffer[$count] = $argument
@ count++
end
# REPLACE command ON THE NEXT LINE WITH
# THE PROGRAM YOU WANT TO CALL.
exec command $buffer[*]
#
toomany:
echo "Too many arguments given."
echo "Usage: foreach_1 [up to 20 arguments]"
exit 1

但是我在尝试运行它时遇到了这个错误:

./foreach_1: line 5: syntax error near unexpected token `('
./foreach_1: line 5: `set buffer = (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)'

我没有任何额外的报价,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

在许多shell中(我相信tcsh算在bourne兼容中),你必须放置表达式的左侧,=和右侧 - 手边所有直接彼此相邻。

# shorten the ` = ` to `=` below:
set buffer=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
set count=1

if ($#argv > 20) goto toomany
#
foreach argument ($argv[*])
set buffer[$count] = $argument
@ count++
end
# REPLACE command ON THE NEXT LINE WITH
# THE PROGRAM YOU WANT TO CALL.
exec command $buffer[*]
#
toomany:
echo "Too many arguments given."
echo "Usage: foreach_1 [up to 20 arguments]"
exit 1