多次使用 args 运行命令

Pol*_*tto 4 command-line bash

我得到了一个包含一些脚本参数的文件:

foo1 a b c
foo2 a b c
foo3 a b c
Run Code Online (Sandbox Code Playgroud)

我需要为此文件中的每一行运行一个脚本,将该行作为脚本 arg 传递,所以它应该这样做:

./MyScript.sh foo1 a b c
./MyScript.sh foo2 a b c
./MyScript.sh foo3 a b c
Run Code Online (Sandbox Code Playgroud)

如何使用 Bash 实现这一目标?

Ser*_*nyy 7

xargs命令,它是为运行带有从标准输入读取的参数的命令而创建的,它有一个--arg-file参数,它允许从文件中读取参数。结合-L1标志,它将逐行读取您的参数文件,并为每一行执行命令。下面是一个例子:

$ cat args.txt
one two three
four file six

$ xargs -L1 --arg-file=args.txt echo                       
one two three
four file six
Run Code Online (Sandbox Code Playgroud)

替换echo为您的脚本。

或者,您始终可以重定向xargs要从 stdin 流读取的文件,如下所示:

$ xargs -L1  echo < args.txt                                                                                             
one two three
four file six
Run Code Online (Sandbox Code Playgroud)


Geo*_*sen 5

使用while循环:

#!/bin/bash
while IFS= read -r line; do
   # if the line read is empty 
   # go to the next line. Skips empty lines
   if [ -z "${line}" ]
   then
       continue
   fi
  /path/to/MyScript.sh $line
done < "$1"
Run Code Online (Sandbox Code Playgroud)

然后调用这个脚本anything.sh并像这样运行它:

anything.sh /path/to/file/with/foo
Run Code Online (Sandbox Code Playgroud)

请记住,对双方anything.shMyScript.sh可执行

  • 您的 for 循环不会逐行读取文件。将其更改为`(IFS=$'\n'; for line in $(cat args.txt); do script.sh "$line"; done)`。一般来说,这不是最好的方法。while 循环更可取 (2认同)
  • `[[ -n "$line" ]] &amp;&amp; ./MyScript.sh $line` 会更短,1 行而不是 5 行 (2认同)