[英]Bash script and manually running commands on the command line
I have the following simple bash script which takes input from stdin and prints the third line given as input. 我有以下简单的bash脚本,该脚本从stdin接收输入并打印出作为输入给出的第三行。
#!/bin/bash
var=$(cat)
echo $var | head -n 3 | tail -n 1
The problem with this script is that it prints all the lines but here is the funny part, when I type the commands individually on the command line I am getting the expected result ie the third line. 该脚本的问题在于它会打印所有行,但这是有趣的部分,当我在命令行上分别键入命令时,我会得到预期的结果,即第三行。 Why this anomaly?
为什么会出现这种异常? Am I doing something wrong here?
我在这里做错什么了吗?
The aim of head -n 3 | tail -n 1
head -n 3 | tail -n 1
的目标head -n 3 | tail -n 1
head -n 3 | tail -n 1
is to keep the third line into variable It will be more efficient to use read builtin head -n 3 | tail -n 1
是将第三行保留为变量使用内建的read会更有效
read
read
read var
echo "${var}"
Or to keep heading white-spaces 还是要保持空白
IFS= read
and not join lines ending with \\
or not give special meaning to \\
而没有加入结尾线
\\
还是不给特殊的意义\\
read -r
You don't need $(cat)
in your script. 您的脚本中不需要
$(cat)
。 If script is reading data from stdin then just have this single line in your script: 如果脚本正在从stdin中读取数据,则只需在脚本中添加以下这一行:
head -n 3 | tail -n 1
And run it as: 并运行为:
bash myscript.sh < file.txt
This will print 3rd line from file.txt
这将从
file.txt
打印第三行
PS: You can replace head + tail
with this faster sed
to print 3rd line from input: PS:您可以使用此更快的
sed
替换head + tail
,以从输入中打印第三行:
sed '3q;d'
The shell is splitting the var
variable so echo get multiple parameters. 外壳正在拆分
var
变量,因此echo获得多个参数。 You need to quote your variable to prevent this to happen: 您需要引用变量以防止这种情况发生:
#!/bin/bash
var=$(cat)
echo "$var" | head -n 3 | tail -n 1
This should do the trick, as far as I understand your question: 据我了解您的问题,这应该可以解决问题:
#!/bin/bash
var=$(cat)
echo "$var" | head -n 3 | tail -n 1
var=$(cat)
will not allow you to escape out of stdin
mode. var=$(cat)
不允许您退出stdin
模式。 you need to specify the EOF
for the script to understand to stop reading from stdin.
您需要为脚本指定
EOF
才能理解以停止从stdin.
读取stdin.
read -d '' var << EOF
echo "$var" | head -n 3 | tail -n 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.