[英]Bash Script, stdin
I have a small problem here. 我这里有一个小问题。
I've written a script, which works fine. 我写了一个脚本,效果很好。 But there is a small problem.
但是有一个小问题。
The script takes 1 or 2 arguments. 该脚本采用1或2个参数。 The 2nd arguments is a .txt file.
第二个参数是一个.txt文件。
If you write something like my_script arg1 test.txt
, the script will work. 如果您编写诸如
my_script arg1 test.txt
之类的脚本,该脚本将起作用。 But when you write my_script arg1 < test.txt
it doesn't. 但是,当您编写
my_script arg1 < test.txt
时却没有。
Here is a demo of my code: 这是我的代码的演示:
#!/bin/bash
if [[ $# = 0 || $# > 2 ]]
then
exit 1
elif [[ $# = 1 || $# = 2 ]]
then
#do stuff
if [ ! -z $2 ]
then
IN=$2
else
exit 3
fi
fi
cat $IN
How can I make it work with my_script arg1 < test.txt
? 如何使其与
my_script arg1 < test.txt
?
If you just want to change how my_script
is called, then just let cat
read from myscript
's standard input by giving it no argument: 如果您只想更改
my_script
的调用方式,则只需不给它参数就让cat
从myscript
的标准输入中读取:
#!/bin/bash
if [[ $# != 0 ]]
then
exit 1
fi
cat
If you want your script to work with either myscript arg1 < test.txt
or myscript arg1 test.txt
, just check the number of arguments and act accordingly. 如果你希望你的脚本与任何工作
myscript arg1 < test.txt
或 myscript arg1 test.txt
,只是检查参数的数量和采取相应的行动。
#!/bin/bash
case $# in
0) exit 1 ;;
1) cat ;;
2) cat $2 ;;
esac
If you look at how the guys at bashnative implemented their cat you should be able to use 'read' to get the piped content.. 如果您看看bashnative的家伙是如何实现他们的猫的,那么您应该能够使用“读取”来获取管道内容。
eg. 例如。 do something like this:
做这样的事情:
while read line; do
echo -n "$line"
done <"${1}"
HTH, HTH,
bovako 博瓦科
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.