bugsyb
bugsyb

Reputation: 6061

How does the "read" command work in Bash functions

Just starting to use bash for the first time (so apologies if this is a dumb question).

As far as I've understood, read is used to receive user input. However, in the example below, it seems that it's also being used to assign function arguments.

Am I missing something here? Is there something else going on? I'm finding it hard to find documentation about how this works.

Any help would be appreciated

function server () {
  while true
  do
    read method path version
    if $method = 'GET'
    then
        echo 'HTTP/1.1 200 OK'
    else
        echo 'HTTP/1.1 400 Bad Request'
    fi
  done
}

Upvotes: 2

Views: 7589

Answers (1)

nigel
nigel

Reputation: 158

In your example, the read command is used to read input into 3 different variables method, path and version.

If the user enters as input the line "my name is joe", then the values of method, path and version are:

method  -> "my"
path    -> "name"
version -> "is joe"

If, however, the user enters "hello world", then only method and path will contain a string. Specifically:

method  -> "hello"
path    -> "world"
version ->

If you want to use the read command to read input into N variables, i.e. read var1 var2 ... varN, the user's input on the command line will be split/ delimited by the characters in the IFS variable. In fact, IFS stands for "Input Field Separators".

By default, the IFS variable is equivalent to $' \t\n'. This means that unless otherwise specified, user inputs are delimited by space, tab or the newline character.

EDIT: IFS is also commonly referred to as the "Internal Field Separator" as David pointed out in the comments (if you see this from other developers).

Upvotes: 4

Related Questions