1

Maybe I'm asking this question wrong, but I can't seem to find the answer to this anywhere. What I'm trying to do is read the lines from a text file passed from the script call (./script.sh textile.txt) and read it into variable. My code is:

function read_hosts{
hosts = $(cat "$1")
}

read_hosts $@

the script call is:

./nexthelper.sh hosts.txt

And, hosts.txt contains the following:

localhost
www.google.com

When I run the code, it throws a syntax error on the hosts = line. Any help would be greatly appreciated!

skye_1019
  • 11
  • 1
  • 3
    Check your scripts with http://shellcheck.net before posting here. – KamilCuk Mar 25 '21 at 15:22
  • Does this answer your question? [Creating an array from a text file in Bash](https://stackoverflow.com/questions/30988586/creating-an-array-from-a-text-file-in-bash) `mapfile -t hosts <"$1"` – Léa Gris Mar 25 '21 at 17:37
  • KamilCuk, I wasn't aware of that website. Thank you for sharing that! LéaGris, I'll check out that page and see if that helps. Thank you! – skye_1019 Mar 26 '21 at 13:42

1 Answers1

1

EDIT After OP confirmed there was no error syntax error around the =

Suggesting this syntax since you are used to C++
The function definition lacks the () to follow the name

function read_hosts(){
    # ...
}

Other syntaxes

  • the () can be ommitted if there is a space or new line after the function name
function function_name {
}
  • the function keyword is optional if () is used

In bash the syntax for assigning values to variables (or setting variables) is

variableName=variableValue

Note the lack of space on either side of the =.

This is because bash splits everything surrounded by spaces into a command. So when you try hosts = "something", bash is essentially trying to execute a command called hosts, then a command called = and a command called something.

Removing the spaces tells bash that you are trying to assign a value to a variable.

Here are some resources I personally use/d for learning bash:

kevinnls
  • 728
  • 4
  • 19
  • Wait... in my code, it isn't spaced out. I'm more used to coding in C++ so I'll space stuff out without thinking about it. it isn't spaced out, and it still throws an error. – skye_1019 Mar 26 '21 at 13:37
  • ah. was focussed on what you had said about the `=` and the spaces that i missed the other syntax error – kevinnls Mar 26 '21 at 15:07
  • added updates. but i'd expect you fixed it by now with [shellcheck.net](//shellcheck.net) – kevinnls Mar 26 '21 at 15:22