本文介绍了在 bash 循环中使用 $#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图理解为什么这个循环没有为提供给脚本的每个参数打印一个数字.
I am trying to understand why this loop does not print a number for each arguments supplied to the script.
#!/bin/bash for i in {1..$#}; do echo $i done相反,当提供时,例如3 个参数,它输出
Instead, when supplied e.g. 3 arguments, it outputs
{1..3} 推荐答案表达式 {} 不接受变量.
The expression {} does not accept variables.
为此,您需要使用例如 seq.以下将使它:
To do so, you need to work with for example seq. The following will make it::
#!/bin/bash for i in $(seq 1 $#); do echo $i done注意 $() 等价于 ``.也就是说,它执行命令替换.例如:
Note that $() is equivalent to ``. That is, it performs a command substitution. For example:
$ d=$(echo "hello") $ echo $d hello您可以在 Shell 编程:什么是$(command) 和 command 的区别.
You can see more information in Shell Programming: What's the difference between $(command) and command.
$ ./a $ $ ./a a b c 1 2 3更多推荐
在 bash 循环中使用 $#
发布评论