Bash / KSH: Define Delimiter (IFS) While Using read Command

The read command in bash and ksh shells is used to read input from the user or from a file. The IFS (Internal Field Separator) environment variable determines the delimiter used when reading input. By default, the IFS is set to space, tab, and newline, which means that input is split into fields based on these characters.

To change the delimiter used by the read command, you need to set the IFS variable to a different value before using the read command. Here’s an example that uses a comma as the delimiter:

IFS=","
read -a fields
echo "Field 1: ${fields[0]}"
echo "Field 2: ${fields[1]}"

In this example, the read command will split the input into fields based on the comma character. The resulting fields are stored in the fields array.

Note: After using the read command, it’s a good idea to reset the IFS back to its original value to avoid any unintended effects on other parts of your script. You can reset the IFS by simply setting it back to its original value, IFS=$' \t\n'.

Leave a Comment