我有一个 bash 脚本,我想遍历 stdin 中的行,或者遍历传入的每个参数。
有没有一种干净的方法来写这个,所以我不必有 2 个循环?
#!/bin/bash
# if we have command line args...
if [ -t 0 ]
then
# loop over arguments
for arg in "$@"
do
# process each argument
done
else
# loop over lines from stdin
while IFS= read -r line; do
# process each line
done
fi
Run Code Online (Sandbox Code Playgroud)
编辑:我正在寻找一个只使用一个循环的通用解决方案,因为我发现我想经常这样做,但总是写出 2 个循环,然后调用一个函数。所以也许某些东西可以将 stdin 变成一个数组,所以我可以使用单个循环来代替?
为您的while read循环创建数据:
#!/bin/sh
if [ "$#" -gt 0 ]; then
# We have command line arguments.
# Output them with newlines in-between.
printf '%s\n' "$@"
else
# No command line arguments.
# Just pass stdin on.
cat
fi |
while IFS= read -r string; do
printf 'Got "%s"\n' "$string"
done
Run Code Online (Sandbox Code Playgroud)
请注意,您的concat示例可以通过while read替换为tr '\n' ','或类似的循环来完成。
此外,该-t测试没有说明您是否有命令行参数。
可替代地,为了处理这两个命令行参数和标准输入(按该顺序):
#!/bin/sh
{
if [ "$#" -gt 0 ]; then
# We have command line arguments.
# Output them with newlines in-between.
printf '%s\n' "$@"
fi
if [ ! -t 0 ]; then
# Pass stdin on.
cat
fi
} |
while IFS= read -r string; do
printf 'Got "%s"\n' "$string"
done
Run Code Online (Sandbox Code Playgroud)
或者,使用一些人似乎喜欢的快捷符号:
#!/bin/sh
{
[ "$#" -gt 0 ] && printf '%s\n' "$@"
[ ! -t 0 ] && cat
} |
while IFS= read -r string; do
printf 'Got "%s"\n' "$string"
done
Run Code Online (Sandbox Code Playgroud)
我们还可以使用标准输入重定向:
#!/usr/bin/env bash
test -t 0 && exec < <(printf '%s\n' "$@")
while IFS= read -r line; do
echo "$line"
done
Run Code Online (Sandbox Code Playgroud)
测试:
test.sh Hello World
test.sh < /etc/passwd
Run Code Online (Sandbox Code Playgroud)