bash - Linux 外壳 : for arg; do

标签 bash for-loop sh posix bashism

阅读 LTP shell code它使用奇怪的 for 循环语法:

for arg; do
    TCID="${TCID}_$arg"
done
  1. 它如何接受参数?我希望它循环遍历 $arg,用 $IFS 分隔,但是当尝试 $arg="aa bb"; 时对于精氨酸;做 echo $arg;完成,它什么都不打印。
  2. 这是一个 bashism 吗?

最佳答案

这是一种使用 for 循环处理命令行选项的特殊方式。

相当于:

for arg in "$@"; do
    TCID="${TCID}_$arg"
done

它不特定于 bash。它在 POSIX 中定义:

The for Loop

The for loop shall execute a sequence of commands for each member in a list of items. The for loop requires that the reserved words do and done be used to delimit the sequence of commands.

The format for the for loop is as follows:

for name [ in [word ... ]] do  
   compound-list  
done

First, the list of words following in shall be expanded to generate a list of items. Then, the variable name shall be set to each item, in turn, and the compound-list executed each time. If no items result from the expansion, the compound-list shall not be executed. Omitting:

in word ...

shall be equivalent to:

in "$@"

关于bash - Linux 外壳 : for arg; do,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73134672/

相关文章:

bash - 在 shell 脚本中隐藏密码

bash - 删除前导和尾随空白目录

r - 嵌套循环用于评估 R 中矩阵的周围单元格

c - 如何替换数组中的子字符串

android - android中的shell脚本给出[: not found

linux - 当我尝试用空格替换新行、制表符和连续空格时,字符 'a' 被删除

linux - 如果在 bash 中运行特定命令,如何获得通知

bash - bash 中的 perl : How to call perl on a script saved in a string

java - 使用 for 循环 Java 理解多线程

linux - 如何使用 bash 命令将文件中的多列合并为一列?