我得到了一个包含一些脚本参数的文件:
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 实现这一目标?
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)
使用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.sh和MyScript.sh可执行
| 归档时间: |
|
| 查看次数: |
2527 次 |
| 最近记录: |