简体   繁体   English

Shell Scripting:在shebang中使用grep和tr

[英]Shell Scripting: Using grep and tr in the shebang

I have this script on my system: 我的系统上有这个脚本:

#! /bin/grep cat

caterpillar
cat
lol
morecat

When I run it, I get the output as expected, 当我运行它时,我得到了预期的输出,

#! /bin/grep cat
caterpillar
cat
morecat

But, if I use tr instead, with the script 但是,如果我使用tr而不是脚本

#! /usr/bin/tr 'a' 'e'

caterpillar
cat
lol
morecat

I expect to get 我希望得到

#! /usr/bin/tr 'a' 'e'

ceterpiller
cet
lol
morecet

But instead nothing is printed, and if I manually type cat , I get c/t . 但是没有打印,如果我手动输入cat ,我会得到c/t How can the script be changed to behave like the first? 如何将脚本更改为像第一个一样?

The shebang line only supports a single argument. shebang行只支持一个参数。 Spaces are included literally and there is no quoting. 字面上包含空格,没有引用。 So the command you're running there is equivalent to this from a shell: 所以你在那里运行的命令与shell相同:

tr "'a' 'e'"

If you run that you'll see that tr complains about the lack of a second argument. 如果你运行它,你会看到tr抱怨缺少第二个参数。 So why does your script not complain? 那么为什么你的剧本不抱怨? Well that's the second problem. 那是第二个问题。 shebang cat or grep works because cat and grep takes name of an input file as an argument, and the shebang adds the script's name to the argument list. shebang catgrep工作,因为catgrep将输入文件的名称作为参数,shebang将脚本的名称添加到参数列表中。 (That's required for the basic case of a #!/bin/sh script to be executed as /bin/sh scriptname ) (这是#!/bin/sh脚本作为/bin/sh scriptname执行的基本情况所必需的)

You are therefore running 你正在跑步

tr "'a' 'e'" yourscriptname

which gives tr the 2 arguments it needs, and it then reads from stdin, translating from a set of characters you didn't intend to another set of characters you didn't intend. 它给了tr它需要的2个参数,然后它从stdin读取,从你不想要的一组字符翻译成你不想要的另一组字符。

If the shebang line had a fully functional shell parser, you could use 如果shebang系列有一个功能齐全的shell解析器,你可以使用

#!/usr/bin/tr 'a' 'e' <

And the filename added to the end would become the input. 添加到末尾的文件名将成为输入。 But shebang is just a simple thing in the kernel, not so featureful. 但是shebang在内核中只是一个简单的东西,并不是那么特别。

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

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