简体   繁体   English

Unix Shell脚本变量声明-找不到命令

[英]unix shell script variable declaration - command not found

nOption=' | awk '{total+=$1} END {print total/1024"kb"}' '
find . -type f -printf "%s %p/n"| sort -nr | head -n10 $nOption

I would like to create a script to find the biggest file at current directory. 我想创建一个脚本来在当前目录中找到最大的文件。 This is my script, there had a error if I use the variable to substitute.... 这是我的脚本,如果我使用变量替代...,则会出现错误。

the output : ./big.sh: line 67: +=: command not found 输出:./big.sh:第67行:+ =:找不到命令

but it works if i do not use variable : 但如果我不使用变量,它就可以工作:

find . -type f -printf "%s %p/n"| sort -nr | head -n10 | awk '{total+=$1} END {print total/1024"kb"}' 

the output is what should i want: 680.021kb 输出就是我想要的:680.021kb

What's wrong of my script?? 我的脚本有什么问题?

thank you 谢谢

Single quoted strings cannot contain other single quotes, so that awk command is interpreted as a shell command instead. 单引号字符串不能包含其他单引号,因此awk命令将解释为Shell命令。 Putting commands in variables is tricky, and in general it's easier, safer and more readable to create a function: 将命令放在变量中是棘手的,通常,创建函数更容易,更安全且更具可读性:

nOption() {
    awk '{total+=$1} END {print total/1024"kb"}'
}
find . -type f -printf "%s %p/n"| sort -nr | head -n10 | nOption

For this specific case, as @chepner points out, the issue is that you can't put command separators such as | 对于这种特殊情况,如@chepner所指出的那样,问题在于您不能放置|等命令分隔符| in a string and then execute that as part of a pipe (without eval , which is evil ). 在字符串中执行,然后将其作为管道的一部分执行(没有eval ,这是邪恶的 )。

The problem is with quotes inside quotes, in variable expansion... 问题在于引号内的引号,变量扩展...
Why don't go with a one-liner? 为什么不选择单线? It's a (tiny) bit faster, and sleeker... :-) (小)更快,并且更时尚... :-)

find . -type f -printf "%s %p/n"| sort -nr | head -n10 | awk '{total+=$1} END {print total/1024"kb"}'

Update : 更新
To make the script more flexible, you could do: 为了使脚本更加灵活,您可以执行以下操作:

dir="."
units="1024"
unitsstring="kb"
find "$dir" -type f -printf "%s %p/n"| sort -nr | head -n10 | awk '{total+=$1} END {print total/$units"$unitsstring"}'

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

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