【问题标题】:Shell script to display the first 12 command-line arguments of the "ls" command用于显示“ls”命令的前 12 个命令行参数的 Shell 脚本
【发布时间】:2018-03-21 04:01:36
【问题描述】:

我正在尝试创建一个与 ls 命令的前 12 个参数相呼应的脚本。我们应该使用内置在 shell 中的“shift”语法来做到这一点,但是我很难理解 shift 命令是如何工作的(是的,我查了一下,试过了,但无法弄清楚)。如果有人能指出如何使用 shift 命令来实现这一目标的正确方向,将不胜感激。我发布了到目前为止我尝试过的内容(公平警告,如果您尝试自己运行它,它会无限循环)

    #!/bin/sh

args=a A b c C d e E f F g h H
while [ $# -lt 12 ]
do
    echo ls -$#
    count=`expr $# + 1`
    shift
done

【问题讨论】:

标签: shell unix scripting


【解决方案1】:

为所有 POSIX shell 处理移位的可靠方法是在 while 循环中使用 $#,使用算术比较 (( $# )),例如

#!/bin/sh

while (( $# )); do
    echo "$1"
    shift
done

使用/输出示例

$ sh shiftargs.sh a A b c C d e E f F g h H
a
A
b
c
C
d
e
E
f
F
g
h
H

【讨论】:

    【解决方案2】:

    shift 删除参数数组的第一个元素。如果您的脚本使用 12 个或更多参数运行,则将跳过循环。如果使用少于 12 个参数运行(如您的示例中),每个参数将被打印,然后关闭。 while 循环条件无限成立,因为数组长度总是小于 12。

    #!/bin/sh
    
    count=0
    while [ $# -gt 0 ] && [ $count -lt 12 ]
    do
        echo ls -$1
        shift
        (( count++ ))
    done
    

    shift reference

    【讨论】:

      【解决方案3】:

      你可以这样做:

      #!/bin/sh
      
      set -- a A b c C d e E f F g h H # set argument list to have 12 values
      i=0
      while ((i < 12)); do             # loop until we scan 12 arguments
        ls -- "$1"                     # do ls with the current argument
        ((i++))
        shift                          # shift left so that $2 becomes $1 and so on
        if (($# == 0)); then break; fi # break if no more arguments
      done
      

      【讨论】:

        最近更新 更多