简体   繁体   English

从shell脚本运行awk文件而不指定awk的确切位置

[英]Run awk file from shell script without specifying awk's exact location

I'm trying to debug a shell script that calls an awk file. 我正在尝试调试调用awk文件的shell脚本。 Which is a nightmare, cause I've never used either before, nor am I very fluent with linux, but anyway 这是一场噩梦,因为我之前从未使用过,也不是我对linux非常流利,但无论如何

A dev made an awk file and is trying to run it in a shell script. 一个dev创建了一个awk文件,并试图在shell脚本中运行它。

To try and run it from a separate location, without needing to specify the exact location, they put the awk script in a folder that's in the PATH variable. 要尝试从单独的位置运行它,而不需要指定确切的位置,他们将awk脚本放在PATH变量中的文件夹中。 So that awk file should be available everywhere, right? 所以awk文件应该随处可用,对吗?

When you run it like this... 当你像这样运行它...

awk -f script.awk arg1 awk -f script.awk arg1

...can awk find that script? ...可以找到那个脚本吗? It spits out an error, when the shell script tries to run that awk command: 当shell脚本尝试运行该awk命令时,它会发出错误:

awk: fatal: can't open source file `script.awk' for reading (No such file or directory) awk:致命:无法打开源文件`script.awk'进行阅读(没有这样的文件或目录)

As you know, awk can't find the script itself. 如您所知, awk无法找到脚本本身。

If the script is marked as executable, and if you have a which command, then you should be able to do: 如果脚本标记为可执行的,如果你有which命令,那么你应该能够做到:

awk -f `which script.awk` arg1

Alternatively, and probably better, make the script into an executable: 或者,可能更好,将脚本变为可执行文件:

#!/usr/bin/awk -f 
BEGIN { x = 23 }
      { x += 2 }
END   { print x }

The shebang needs the ' -f ' option to work on MacOS X 10.7.1 where I tested it: shebang需要' -f '选项才能在我测试的MacOS X 10.7.1上运行:

$ script.awk script.awk
31
$

That gives you a self-contained single-file solution. 这为您提供了一个独立的单文件解决方案。

No, that's not going to work. 不,那不行。 awk needs the path to the script to run, it won't use the PATH variable to find it. awk需要运行脚本的路径,它不会使用PATH变量来查找它。 PATH is only used to find executables. PATH仅用于查找可执行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM