区分不同类型的输入(BASH)
我有一个脚本,它必须能够在第一个参数上同时接受byfiles和stdin。如果参数多于或少于1个,则拒绝它们 我试图实现的目标是能够使用此格式进行accpet区分不同类型的输入(BASH),bash,Bash,我有一个脚本,它必须能够在第一个参数上同时接受byfiles和stdin。如果参数多于或少于1个,则拒绝它们 我试图实现的目标是能够使用此格式进行accpet ./myscript myfile AND ./myscript < myfile fi 问题是当我试图说 ./myscript < myfile 我不知道这是否是正确的方法来做这件事,我真的很感谢建议或正确的代码为我的问题。谢谢你/bin/bash #!/bin/bash # if nothing passe
./myscript myfile
AND
./myscript < myfile
fi
问题是当我试图说
./myscript < myfile
我不知道这是否是正确的方法来做这件事,我真的很感谢建议或正确的代码为我的问题。谢谢你/bin/bash
#!/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
#如果在命令行中没有传递任何内容,请将“/dev/stdin”传递给我自己
#所以下面所有的代码都可以免费使用
[${}-gt 0]| | set--/dev/stdin
#循环遍历命令行参数,将其视为文件名
对于“$@”中的f;做
回声$f
[[-r$f]]&&whilereadline;执行echo“echo:”$line;完成<$f
完成
示例:
$ args.sh < input.txt
$ args.sh input.txt
$ cat input.txt | args.sh
$args.sh
将文件内容读取到脚本中。它不会因为我只是在没有解释的情况下转储代码而对该文件投反对票。谢谢你添加了解释。删除下一票。set--/dev/stdin
将一个参数设置为文本字符串/dev/stdin
@999999999999999999999999999999 - 很好的观察,这就是它的作用/dev/stdin是Posix OS es中的一个特殊文件,其中“包含”进程的标准输入
#!/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