Reputation: 1017
a=1
echo -n "Enter book id: "; read book_id;
while [ $a -eq 1 ]
do
a=$(awk '{ if($3 == "$book_id") print 1; else print 0}' exercise1_data.txt)
echo $a
if [ $a -eq 1 ]; then
echo -n "Please enter unique book id: "; read book_id
fi
done
I am trying to check if the book id entered by the user is unique or not. What I am doing is checking in the file "exercise1_data.txt" if there is any instance of "book_id". The while loop is to be executed until the user inputs a unique book id.
I am getting an error Too many arguments
Upvotes: 1
Views: 244
Reputation: 85883
Firstly fixing the awk:
You need to pass shell variables to awk
using the -v
option:
awk -v b_id="$book_id" '$3==b_id{print 1;exit}END{print 0}' exercise1_data.txt
Also if $3==b_id
you should print 1
and exit
as a match is found. Only print 0
when we reach the end of file (no match found).
Secondly the script:
$ cat file
book_1 orielly 100
book_2 wiley 101
Script:
#!/bin/bash
a=1
while [ "$a" -eq 1 ]; do
echo -n "Please enter unique book id: "
read book_id
let a=$(awk -v b_id="$book_id" '$3==b_id{print 1;exit}END{print 0}' file)
echo "$a"
done
Demo:
$ bash script.sh
Please enter unique book id: 100
1
Please enter unique book id: 101
1
Please enter unique book id: 102
0
Notes:
Always quotes your shell variables.
You are using whitespace as a field separator in the book file this won't be flexible i.e books titles, authors ect all have whitespace.
Upvotes: 2