2
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

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

What's wrong of my script??

thank you

1

2 Answers 2

4

Single quoted strings cannot contain other single quotes, so that awk command is interpreted as a shell command instead. 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 | in a string and then execute that as part of a pipe (without eval, which is evil).

Sign up to request clarification or add additional context in comments.

1 Comment

Right answer, but the real problem, even if quoting were done correctly, is that you can't put shell syntax in a parameter like the OP tried. noption="| awk '...'" (with proper quoting and escaping in the awk script itself) would still fail, because the | would be treated as a literal character and therefore just another argument to head.
0

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"}'

2 Comments

thank you. It is because this is a part of my script, I would like to change the nOption at some situation.
I see. But I think it's not possible to expand a variable ($1) inside a variable ($nOption). Flexibility is not obtained putting a command inside a variable, usually... You should select which parts of your command (string "kb", for example?) could change, in the future, and put these inside variables... See my updated answer to see an example... See also l0b0's answer, it's a different approach...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.