使用参数 2 直到 @ for 循环

Fl.*_*pf. 5 bash

我有一个外壳脚本:

#!/bin/bash
exec_command -k -q $1

for i in $@
do
  grep --color=always "$i" file
done
Run Code Online (Sandbox Code Playgroud)

我将脚本称为

./grepskript -v searchstring1 searchstring2
Run Code Online (Sandbox Code Playgroud)

我想使用循环的第一个参数exec_command和所有其他参数do。我该怎么做?

Ini*_*ian 10

根据需要使用该shift命令推送位置参数。在您的情况下,doingshift 1会将$1(即第一个参数)与其余的参数分开。类似地,shift 2将从参数列表中移动前 2 个参数,依此类推。并且始终记住引用您的变量/参数,以免被 shell 进行分词。

#!/bin/bash

exec_command -k -q "$1"
shift 1

for i in "$@"; do
  grep --color=always "$i" file
done
Run Code Online (Sandbox Code Playgroud)

请参阅shift手册页以了解更多信息。这是一个跨 shell 可用的 POSIX 兼容选项。

或者另一种方法bash在参数列表上执行(特定)基于索引的扩展$@,如下所示,从病房的第二个元素开始循环。

#!/bin/bash

exec_command -k -q "$1"

for i in "${@:2}"; do
  grep --color=always -- "$i" file
done
Run Code Online (Sandbox Code Playgroud)

此外,在第一种方法中迭代位置参数时,您只需

for i; do
  grep --color=always -- "$i" file
done
Run Code Online (Sandbox Code Playgroud)