我有一个脚本必须能够在第一个参数上接受文件和stdin。然后,如果多于或少于1个参数,拒绝它们
我正在努力实现的目标是能够使用这种格式
./myscript myfile
AND
./myscript < myfile
到目前为止我所拥有的是
if [ "$#" -eq 1 ]; then #check argument
if [ -t 0 ]; then #check whether input from keyboard (read from github)
VAR=${1:-/dev/stdin} #get value to VAR
#then do stuff here!!
else #if not input from keyboard
VAR=$1
if [ ! -f "$VAR" ]; then #check whether file readable
echo "ERROR!"
else
#do stuff heree!!!
fi
fi
网络连接
问题是我试图说的时候
./myscript < myfile
打印
ERROR!
我不知道这是否是正确的方法,我真的很感谢建议或我的问题的正确代码。谢谢
答案 0 :(得分:1)
#!/bin/bash
# if nothing passed in command line pass "/dev/stdin" to myself
# so all below code can be made branch-free
[[ ${#} -gt 0 ]] || set -- /dev/stdin
# loop through the command line arguments, treating them as file names
for f in "$@"; do
echo $f
[[ -r $f ]] && while read line; do echo 'echo:' $line; done < $f
done
示例:
$ args.sh < input.txt
$ args.sh input.txt
$ cat input.txt | args.sh