[英]Alias bash one line script
I have to do an alias called for example "longest" for this script:我必须为此脚本做一个别名,例如“最长”:
data=""; len=0; line=""; while [[ $line != "quit" ]]; do read line; [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line; done; echo $len; echo $data 1>2
Its job is simply reading words or phrases and counting the characters.它的工作只是阅读单词或短语并计算字符。
I put the script inside quotes like this:我将脚本放在引号中,如下所示:
alias longest="...script..."
but it doesn't work and I don't know why.但它不起作用,我不知道为什么。 Can anyone explain to me why?
谁能向我解释为什么? A possible solution?
一个可能的解决方案?
You have several options (and I'm repeating the script from the question, not fixing any other errors (?) like redirecting to a file with name 2
):您有几个选项(我正在重复问题中的脚本,而不是修复任何其他错误(?),例如重定向到名称为
2
的文件):
Have the alias define a function and execute it immediately让别名定义一个函数并立即执行它
alias longest='f() { data=""; len=0; line=""; while [[ $line != "quit" ]]; do read line; [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line; done; echo $len; echo $data 1>2; }; f'
Create a script and save it in a directory from your PATH
, usually ~/bin
:创建一个脚本并将其保存在
PATH
的目录中,通常是~/bin
:
File ~/bin/longest
:文件
~/bin/longest
:
#!/bin/bash data=""; len=0; line=""; while [[ $line != "quit" ]]; do read line; [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line; done; echo $len; echo $data 1>2
and finally chmod +x ~/bin/longest
.最后
chmod +x ~/bin/longest
。
Define the function in your .bashrc
file and then call it on demand.在
.bashrc
文件中定义函数,然后按需调用它。
Avoid the complicated, home-grown code and go for something much simpler .避免使用复杂的本土代码,选择更简单的代码。 The behavior and output will not be identical, but should be sufficient.
行为和输出不会相同,但应该足够了。
alias longest="awk '{print length, \$0}' | sort -nr | head -1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.