Using $# in bash loops

早过忘川 提交于 2019-12-13 04:35:30

问题


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

Instead, when supplied e.g. 3 arguments, it outputs

{1..3}

回答1:


The expression {} does not accept variables.

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

You can see more information in Shell Programming: What's the difference between $(command) and command.

Tests

$ ./a
$

$ ./a a b c
1
2
3



回答2:


Brace expansion occurs before variable expansion

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions



来源:https://stackoverflow.com/questions/18979681/using-in-bash-loops

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!