Attempted to use awk sqrt but only returns 0

本秂侑毒 提交于 2019-12-08 07:16:44

问题


I am attempting to use the sqrt function from awk command in my script, but all it returns is 0. Is there anything wrong with my script below?

echo "enter number"
read root
awk 'BEGIN{ print sqrt($root) }'

This is my first time using the awk command, are there any mistakes that I am not understanding here?


回答1:


Maybe you can try this.

echo "enter number"
read root
echo "$root" | awk '{print sqrt($0)}'

You have to give a data input to awk. So, you can pipe 'echo'. The BEGIN statement is to do things, like print a header...etc before awk starts reading the input.




回答2:


$ echo "enter number"
enter number
$ read root
3
$ awk -v root="$root" 'BEGIN{ print sqrt(root) }'
1.73205

See the comp.unix.shell FAQ for the 2 correct ways to pass the value of a shell variable to an awk script.




回答3:


UPDATE : My proposed solution turns out to be potentially dangerous. See Ed Morton's answer for a better solution. I'll leave this answer here as a warning.

Because of the single quotes, $root is interpreted by awk, not by the shell. awk treats root as an uninitialized variable, whose value is the empty string, treated as 0 in a numeric context. $root is the root'th field of the current line -- in this case, as $0, which is the entire line. Since it's in a BEGIN block, there is no current line, so $root is the empty string -- which again is treated as 0 when passed to sqrt().

You can see this by changing your command line a bit:

$ awk 'BEGIN { print sqrt("") }'
0
$ echo 2 | awk '{ print sqrt($root) }'
1.41421

NOTE: The above is merely to show what's wrong with the original command, and how it's interpreted by the shell and by awk.

One solution is to use double quotes rather than single quotes. The shell expands variable references within double quotes:

$ echo "enter number"
enter number
$ read x
2
$ awk "BEGIN { print sqrt($x) }" # DANGEROUS
1.41421

You'll need to be careful when doing this kind of thing. The interaction between quoting and variable expansion in the shell vs. awk can be complicated.

UPDATE: In fact, you need to be extremely careful. As Ed Morton points out in a comment, this method can result in arbitrary code execution given a malicious value for $x, which is always a risk for a value read from user input. His answer avoids that problem.

(Note that I've changed the name of your shell variable from $root to $x, since it's the number whose square root you want, not the root itself.)



来源:https://stackoverflow.com/questions/38575282/attempted-to-use-awk-sqrt-but-only-returns-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!