gpt4 book ai didi

linux - shell 脚本 : Using grep and tr in the shebang

转载 作者:IT王子 更新时间:2023-10-29 01:00:47 25 4
gpt4 key购买 nike

我的系统上有这个脚本:

#! /bin/grep cat

caterpillar
cat
lol
morecat

当我运行它时,我得到了预期的输出,

#! /bin/grep cat
caterpillar
cat
morecat

但是,如果我改用 tr,在脚本中

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

caterpillar
cat
lol
morecat

我希望得到

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

ceterpiller
cet
lol
morecet

但是没有打印任何内容,如果我手动键入 cat,我会得到 c/t。如何更改脚本使其表现得像第一个脚本?

最佳答案

shebang 行只支持一个参数。空格按字面意思包含,没有引用。所以你在那里运行的命令等同于 shell 中的命令:

tr "'a' 'e'"

如果你运行它,你会看到 tr 提示缺少第二个参数。那么为什么你的脚本没有提示?那么这是第二个问题。 shebang catgrep 之所以有效,是因为 catgrep 将输入文件的名称作为参数,而 shebang将脚本的名称添加到参数列表中。 (这是 #!/bin/sh 脚本作为 /bin/sh scriptname 执行的基本情况所必需的)

因此你在运行

tr "'a' 'e'" yourscriptname

它为 tr 提供它需要的 2 个参数,然后它从 stdin 读取,将一组你不想要的字符转换为另一组你不想要的字符。

如果 shebang 行有一个功能齐全的 shell 解析器,你可以使用

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

添加到末尾的文件名将成为输入。但是shebang只是内核中的一个简单的东西,没有那么有特色。

关于linux - shell 脚本 : Using grep and tr in the shebang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com