tags:

views:

45

answers:

3

I have to put in a bash variable the first line of a file. I guess it is with the grep command, but it is any way to restrict the number of lines?

Thanks in advance

+3  A: 

head takes the first lines from a file, and the -n parameter can be used to specify how many lines should be extracted:

line=$(head -n 1 filename)
sth
A: 
line=$(head -1 file)

Will work fine. (As previous answer). But

line=$(read -r FIRSTLINE < filename)

will be marginally faster as read is a built-in bash command.

jackbot
Please fix back-tick formatting
Tadeusz A. Kadłubowski
Second method doesn't work as written, because `read` doesn't print anything (so `line` winds up blank), and also executes in a subshell (so `FIRSTLINE` gets set to the first line, but only in the subshell, so it's not available afterward). Solution: just use `read -r line <filename`
Gordon Davisson
A: 

to read first line using bash, use read statement. eg

read -r firstline<file

firstline will be your variable (No need to assign to another)

ghostdog74