0

I am doing basic programs with Linux shell scripting(bash)

I want to read the first line of a file and store it in a variable .

My input file :

100|Surender|CHN
101|Raja|BNG
102|Kumar|CHN

My shell script is below

first_line=cat /home/user/inputfiles/records.txt | head -1
echo $first_line

I am executing the shell script with bash records.sh

It throws me error as

 /home/user/inputfiles/records.txt line 1: command not found

Could some one help me on this

Trevor
  • 1,111
  • 2
  • 18
  • 30
Surender Raja
  • 3,553
  • 8
  • 44
  • 80

2 Answers2

1

The line

first_line=cat /home/user/inputfiles/records.txt | head -1

sets variable first_line to cat and then tries to execute the rest as a command resulting in an error.

You should use command substitution to execute cat .../records.txt | head -1 as a command:

first_line=`cat /home/user/inputfiles/records.txt | head -1`
echo $first_line
vitaut
  • 49,672
  • 25
  • 199
  • 336
1

The other answer addresses the obvious mistake you made. Though, you're not using the idiomatic way of reading the first line of a file. Please consider this instead (more efficient, avoiding a subshell, a pipe, two external processes among which a useless use of cat):

IFS= read -r first_line < /home/user/inputfiles/records.txt
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104