bashunix-head

How can I use 'head' in a bash script with a variable?


I've been trying to create a script that can read a certain line off of a file given some variables I've created.

SCRIPTNUM=$(tail -1 leet.txt)
LINE=$(echo $SCRIPTNUM | python leetSolver.py)
PART1=$(head "-$LINE" leet.txt)
FLAG=$(printf "$PART1" | tail -1)
FLAGFORMAT="$FLAG\n"
printf $FLAGFORMAT

From this the biggest problem I face is that I get this error:

head: invalid trailing option -- 
Try `head --help' for more information.

The code works just fine when inputted through the terminal one line at a time. Is there a way to make this code work? It's worth noting that using a constant (ie head -5) works.


Solution

  • A quick test here seems to indicate that the problem is that your $LINE variable has trailing spaces (i.e. '5 ' instead of '5'). Try removing them.

    $ head '-5g' file
    head: invalid trailing option -- g
    Try `head --help' for more information.
    
    $ head '-5.' file
    head: invalid trailing option -- .
    Try `head --help' for more information.
    
    $ head '-5 ' file
    head: invalid trailing option --
    Try `head --help' for more information.