0

I'm using bash select menu's to create a quick cli to interact with an API. Right now all is working well with the individual/prompted show, add, update, delete. I'm having a problem with the bulk "operation" which will be reading from a file, e.g:

10.10.0.0/20,test,true
100.100.1.2/32,test,false
11.11.1.0/28,test,false

and set the values as variables into a payload variable. This is the variable working well in all code.

PAYLOAD="{\"prefix\": \"$prefix\", \"comment\": \"$comment\", \"enabled\": $status}"

To read from the file and split the commas I'm doing:

#!/bin/bash
# To read values from file
#set -x    
file="`pwd`/ips.txt"
while IFS=, read -r f1 f2 f3
do
PAYLOAD="{\"prefix\": \"$f1\", \"comment\": \"$f2\", \"enabled\": $f3}"
echo "$PAYLOAD"
#curl_api "$url" "POST" "$PAYLOAD" 
done < $file

However when displaying the payload i'm getting the payload variable with the curly brackets all messed up:

}"prefix": "100.10.0.0/20", "comment": "test", "enabled": true
}"prefix": "100.100.1.2/32", "comment": "test", "enabled": false
}"prefix": "11.11.1.0/28", "comment": "test", "enabled": false

This makes the API call to fail... and I'm struggling to understand why the brackets don't open/close {} as expected:

{"prefix": "100.10.0.0/20", "comment": "test", "enabled": true}
{"prefix": "100.100.1.2/32", "comment": "test", "enabled": false}
{"prefix": "11.11.1.0/28", "comment": "test", "enabled": false}

Thanks in advance to anyone that takes time to read and help on this post.

RPopas
  • 1
  • looks like your data file may have windows/dos line endings (ie, `\r\n`); you can verify this by running `od -c ips.txt` and if I'm correct then you'll notice the following characters in the output: `\r \n`; another option is to add `typeset -p f3` inside the `while` loop and you should see the `f3` variable has a `\r` at the end of its value; there a few ways to go aboud removing the `\r` but the easiest would be to pre-process the file like such: `dos2unix ips.txt` ... this willl remove the `\r` characters from the file after which your code should generate the desired output – markp-fuso Jul 24 '22 at 16:20
  • fwiw, the `\r` is a 'carriage return' which says to move the cursor back to the front of the current line, so if `f3=true\r` your `echo` will print `true` at the end of the line, move the cursor back to the front of the line and *then* print the `}`; the trailing `}` is printed at the front of the line, overwriting the initial character printed at the front of the line, ie, the `{` – markp-fuso Jul 24 '22 at 16:23
  • 1
    wow, you nailed it thank you very much i did created the file on linux and tested and works well: ./read_file.sh {"prefix": "1.1.1.1/32", "comment": "test2", "enabled": false} – RPopas Jul 24 '22 at 16:30

0 Answers0