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,072
  • 1
  • 18
  • 27
Surender Raja
  • 3,377
  • 7
  • 37
  • 68

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
  • 43,200
  • 23
  • 168
  • 291
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
  • 41,910
  • 9
  • 88
  • 99