在 bash 循环中使用 $#

编程入门 行业动态 更新时间:2024-10-27 08:26:43
本文介绍了在 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 循环中使用 $#

本文发布于:2023-10-26 01:22:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528667.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!