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

15.6k Views Asked by At

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.

2

There are 2 best solutions below

6
On BEST ANSWER

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.
2
On

Change this line

LINE=$(echo $SCRIPTNUM | python leetSolver.py)

to

LINE=$(echo $SCRIPTNUM | python leetSolver.py | tr -d '\r\n ')

that will remove any trailing line feeds or carriage returns or spaces.

Or, if you prefer sed

LINE=$(echo $SCRIPTNUM | python leetSolver.py | sed 's/[^0-9]//g' )

Or, if you like tr

LINE=$(echo $SCRIPTNUM | python leetSolver.py | tr -cd '[:digit:]' )

will remove all non-digits.