bash 脚本中的参数
Argument in bash script
我有以下 bash 脚本,名为 countscript.sh
1 #!/bin/bash
2 echo "Running" [=11=]
3 tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed q
但是我不明白如何正确传递参数:("3"应该是sed的参数$1)。
$ echo " one two two three three three" | ./countscript.sh 3
Running ./countscript.sh
sed: -e expression #1, char 1: missing command
这很好用:
$ echo "one two three four one one four" | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3q
3 one
2 four
1 two
谢谢。
PS:还有人注意到
第 10 页的脚本中存在错误,https://www.cs.tufts.edu/~nr/cs257/archive/don-knuth/pearls-2.pdf ?
当运行以下命令时:
$ echo " one two two three three three" | ./countscript.sh 3
特殊变量 </code> 将替换为 <code>3
,您的第一个参数。因此,脚本运行:
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3 q
注意 3
和 q
之间的 space。 sed
不知道该怎么做,因为你没有给它命令(3
不是命令)。
删除 space,你应该没问题。
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed "q"
引用的论文,我觉得你看错了
sed q
为
sed q
和 sed
本身不认为 3
是有效命令。单独的参数 q
被视为输入文件名。如果 </code> <em>did</em> 的值导致单个有效的 <code>sed
脚本,您可能会收到缺少输入文件 q
的错误。
正确的 shell 编程会要求写成
sed "q"
或
sed " q"
相反;将 space 作为脚本的 部分 ,sed
正确输出第一 </code> 行输入并退出。</p>
<hr />
<p>有点奇怪作者使用 <code>sed
而不是 head - ""
来输出前几行,因为他们中的一个人 (McIlroy) 基本上发明了 Unix 管道的想法作为一系列special-purpose,狭义的工具。没有阅读整篇论文,我不知道 Knuth 和 McIlroy 对这篇论文的贡献是什么;也许 Bentley 只是喜欢 sed
。 :)
我有以下 bash 脚本,名为 countscript.sh
1 #!/bin/bash
2 echo "Running" [=11=]
3 tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed q
但是我不明白如何正确传递参数:("3"应该是sed的参数$1)。
$ echo " one two two three three three" | ./countscript.sh 3
Running ./countscript.sh
sed: -e expression #1, char 1: missing command
这很好用:
$ echo "one two three four one one four" | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3q
3 one
2 four
1 two
谢谢。
PS:还有人注意到
第 10 页的脚本中存在错误,https://www.cs.tufts.edu/~nr/cs257/archive/don-knuth/pearls-2.pdf ?
当运行以下命令时:
$ echo " one two two three three three" | ./countscript.sh 3
特殊变量 </code> 将替换为 <code>3
,您的第一个参数。因此,脚本运行:
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 3 q
注意 3
和 q
之间的 space。 sed
不知道该怎么做,因为你没有给它命令(3
不是命令)。
删除 space,你应该没问题。
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed "q"
引用的论文,我觉得你看错了
sed q
为
sed q
和 sed
本身不认为 3
是有效命令。单独的参数 q
被视为输入文件名。如果 </code> <em>did</em> 的值导致单个有效的 <code>sed
脚本,您可能会收到缺少输入文件 q
的错误。
正确的 shell 编程会要求写成
sed "q"
或
sed " q"
相反;将 space 作为脚本的 部分 ,sed
正确输出第一 </code> 行输入并退出。</p>
<hr />
<p>有点奇怪作者使用 <code>sed
而不是 head - ""
来输出前几行,因为他们中的一个人 (McIlroy) 基本上发明了 Unix 管道的想法作为一系列special-purpose,狭义的工具。没有阅读整篇论文,我不知道 Knuth 和 McIlroy 对这篇论文的贡献是什么;也许 Bentley 只是喜欢 sed
。 :)