在 bash 循环中使用 $# [英] Using $# in bash loops

查看:64
本文介绍了在 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 循环中使用 $#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆