bash shell脚本中的grep不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5822383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:52:40  来源:igfitidea点击:

grep inside shell script not working

bashshellgrep

提问by

When I run this on the command line it works:

当我在命令行上运行它时,它可以工作:

ls | grep -v "#$"

But when I do ls | scriptnameand inside the script I have:

但是当我ls | scriptname在脚本中这样做时,我有:

#fileformat=unix
#!/bin/bash
grep -iv '#$'

It's not working. Why?

它不工作。为什么?

[EDIT]

[编辑]

the reason for the first line is explained here.

此处解释了第一行的原因。

besides that even if i remove the first two lines it SHOULD work. i tried the exact same on a remote Solaris account and it did work. so is it my Fedora installation?

除此之外,即使我删除了前两行,它也应该可以工作。我在远程 Solaris 帐户上尝试了完全相同的方法,并且确实有效。所以这是我的 Fedora 安装吗?

采纳答案by John Kugelman

The hash-bang line needs to be the first line in the script. Get rid of the #fileformat=unix. Also make sure your script is executable (chmod +x scriptname). This works:

hash-bang 行需要是脚本中的第一行。摆脱#fileformat=unix. 还要确保您的脚本是可执行的 ( chmod +x scriptname)。这有效:

#!/bin/bash
grep -iv '#$'

回答by shellter

1st off you need #! /bin/bash as the first line in your script.

第一关你需要#! /bin/bash 作为脚本中的第一行。

Then '#$' has no meaning in the shell pantheon of parameters. Are you searching for a '#' at the end of the line? (That is OK). But if you meant '$#' but then $# is the parameter that means the 'number of arguments on the command-line'

那么'#$'在参数的shell万神殿中没有意义。您是否在行尾搜索“#”?(那没问题)。但是,如果您的意思是 '$#' 但 $# 是表示“命令行上的参数数量”的参数

Generally, piping a list of files to a script to acted on would have to be accomplished with further wrapper. So a bare-bones, general solution to the problem you pose might be :

通常,将文件列表通过管道传输到要执行的脚本必须使用进一步的包装器来完成。因此,您提出的问题的基本解决方案可能是:

$cat scriptname
#!/bin/bash

while read fileTargs ; do
   grep -iv "${@}" ${fileTargs}   # (search targets).
done

called as

称为

ls | scriptname srchTargets

I hope this helps.

我希望这有帮助。

回答by ljkyser

Change it to ls < scriptnameso that the output is passed to ls.

将其更改为,ls < scriptname以便将输出传递给 ls。