G.kalyan
G.kalyan

Reputation: 41

Read a file in a shell script

I want to read a file in a shell script with comparing to a given user data

Ex:-

file: vm_list.txt having following data

vm1,vm2,vm3

user given as parameter vm2,vm4

First it will read vm_list.txt file and compare user given parameters vm2,vm4. If it's a valid vm give output as valid if not this vm does not exist or given wrong vm name.

I tried below logic but I'm not able to achieve the correct result.

code:

for vm_name in "${vm_names[@]}"
do
  VM_LIST_FILE="/tmp/$AZ_ACCOUNT.vm.list"
  az vm list --output table > "$VM_LIST_FILE"
  vm_rg_name=$(grep $vm_name "${VM_LIST_FILE}" |
               awk '{ print $2 }' | tr '[:upper:]' '[:lower:]')
  if cat $VM_LIST_FILE | grep '$vm_name'; then
     echo "This vm $vm_name is Present on $vm_rg_name"
  else
     echo "This vm $vm_name is not present or invalid vm Name"
  fi
done

Upvotes: 0

Views: 165

Answers (1)

Jens
Jens

Reputation: 72639

One problem is the single quoting in

cat $VM_LIST_FILE | grep '$vm_name'

This will not substitute $vm_name. You need to use double quotes:

grep "$vm_name" $VM_LIST_FILE

and save a useless cat on the way.

Besides from this, grep|awk is an anti-pattern, because awk can do the grepping: awk '/pattern/ { action }' is what should be used instead.

Upvotes: 1

Related Questions