0

I try to customize a little BASH script for special proprose.

I'm confuse with BASH scripting when it come time to assigne a command to a variable.

My broken code:

if [ -n "$2" ]
then
    top=`| head -n $2`
fi
awk '{print $17, ">", $19;}' $logs_folder$i | sort -g | uniq -c | sort -r -g $top

So by default it return all line but if the user specified a number, it will add the head command

1

2 Answers 2

1

Use array form instead:

if [ -n "$2" ]
then
    top=(head -n "$2")
else
    top=(cat)
fi
awk '{print $17, ">", $19;}' "$logs_folder$i" | sort -g | uniq -c | sort -r -g | "${top[@]}"

And try to add more quotes ("").

Actually you can't save pipe to a variable and let bash parse it the normal way when it's expanded but you can replace it with another command instead (cat).

You could actually use eval but it's pretty delicate:

if [ -n "$2" ]
then
    top="| head -n \"\$2\""
fi
eval "awk '{print $17, \">\", \$19;}' \"\$logs_folder\$i\" | sort -g | uniq -c | sort -r -g $top"
Sign up to request clarification or add additional context in comments.

1 Comment

Nice try to remplace it with cat. Thanks
0

A working script would look like this:

# set propper default value
top=""
if [ -n "$2" ]
then
    # use double quotes instead of back-tics
    # back-tics are for command substitution
    # but you need the command itself as a string
    top="| head -n $2"
fi

awk '{print $17, ">", $19;}' "$logs_folder$i" | sort -g | uniq -c | sort -r -g $top

Comments

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.