0

I have store ip address with port in a file and I want to read it using shell script. Thus file serverIP has data 192.168.1.17:3000. I am using following bash script to read it

IPAddressFile=/home/geo/serverIP SERVER_IP_PORT=$(<$IPAddressFile) echo $SERVER_IP_PORT 

But this script echo empty string. Where I am making mistake?

7
  • 1
    Can't replicate with the commands you show. Did you copy-paste the script into the question? If not, is everything spelled correctly in the script? Commented Jan 15, 2019 at 13:01
  • Possible duplicate. Please refer to this anser: How to read a file into a variable in shell? Commented Jan 15, 2019 at 13:05
  • No I am following the same code in given accepted answer but it's not working my case and that's why I have posted this question Commented Jan 15, 2019 at 13:08
  • 2
    How are you running the script? If you run sh yourscript it won't have bash-only extensions such as $(<...); it must be invoked with bash as the shell. Commented Jan 15, 2019 at 13:09
  • 2
    Don't. If you want to use bash syntax, you must bash scriptfile, or set it executable with a #!/bin/bash shebang and run ./scriptfile. Commented Jan 15, 2019 at 13:09

1 Answer 1

2

If you're going to use bash-only syntax like $(<...), your script must be run with bash, not sh.

Thus, either run bash yourscript or add a #!/bin/bash (or similar) shebang, flag the file executable, and invoke it as a command, for example ./yourscript


As an alternative that's both efficient and compatible with POSIX sh:

IFS= read -r SERVER_IP_PORT <"$IPAddressFile" 
Sign up to request clarification or add additional context in comments.

7 Comments

What? Charles Duffy is not using "${IPAddressFile}"?
@hek2mgl, ...when did I ever support use of braces in contexts where they're not necessary for correctness or clarity? You must be thinking of someone else. :)
...now, what is unlike me is failing to lecture the OP about their use of all-caps names for self-defined variables :)
I was thinking that when people just consequently use them, they will never have to spent time thinking about if they have to use them, or forget them. And it gives a cleaner overall picture of the code.
nod, that's a very defensible position; I certainly won't say you're wrong. OTOH, most of the shell scripts I write outside Stack Overflow these days are being embedded in Nix code, and Nix uses ${...} as an escape to embed a Nix expression in a string unless escaped as ''${...} -- so it'd be a bit painful to follow that convention in my real-world day-to-day.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.