gpt4 book ai didi

linux - bash 脚本读取管道或参数

转载 作者:IT王子 更新时间:2023-10-29 00:40:04 27 4
gpt4 key购买 nike

我希望我的脚本从 stdin 中读取一个字符串,如果它是通过管道传输的,或者从一个参数中读取。所以首先我想检查一些文本是否通过管道传输,如果没有,它应该使用一个参数作为输入。我的代码看起来像这样:

value=$(cat) # read from stdin
if [ "$pipe" != "" ]; then #check if pipe is not empty
#Do something with pipe string
else
#Do something with argument string
fi

问题是当它没有通过管道传输时,脚本将停止并等待“ctrl d”,我不希望这样。关于如何解决这个问题有什么建议吗?

提前致谢。/托马斯

最佳答案

先检查参数怎么样?

if (($#)) ; then
process "$1"
else
cat | process
fi

或者,利用 cat 的相同行为:

cat "$@" | process

关于linux - bash 脚本读取管道或参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351261/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com