How to use the command IFS (Internal Field Separator) (with examples)
The IFS (Internal Field Separator) is a special environment variable in Unix shells that defines the delimiter used for word splitting. By default, the IFS value is set to a space, tab, and newline, which serve as delimiters. However, it can be changed to a different delimiter as per the requirements.
Use case 1: View the current IFS value
Code:
echo "$IFS"
Motivation: You may want to view the current IFS value in order to determine which delimiter is being used for word splitting in your shell.
Explanation:
The echo
command is used to display the current value of IFS. The $IFS
is used to access the value of the IFS environment variable.
Example output:
(space) (tab) (newline)
Use case 2: Change the IFS value
Code:
IFS=":"
Motivation: You might need to change the IFS value to a different delimiter, such as a colon, to customize the word splitting behavior in your shell. This can be useful when processing files or data with different delimiters.
Explanation:
The IFS=":"
command assigns the value of “:” to the IFS environment variable, changing the delimiter used for word splitting to a colon.
Example output:
No output is displayed after executing this command. To verify the new IFS value, you can use the echo "$IFS"
command.
Use case 3: Reset IFS to default
Code:
IFS=$' \t\n'
Motivation: If you have previously changed the IFS value and want to revert it back to the default delimiter (space, tab, newline), this use case is suitable.
Explanation:
The IFS=$' \t\n'
command assigns the value of “space”, “tab”, and “newline” to the IFS environment variable, resetting it to the default delimiter.
Example output:
No output is displayed after executing this command. To verify the new IFS value, you can use the echo "$IFS"
command.
Use case 4: Temporarily change the IFS value in a subshell
Code:
(IFS=":"; echo "one:two:three")
Motivation: Sometimes, you may want to change the IFS value only temporarily within a specific block of code, rather than globally for the entire shell session. This use case allows you to achieve that by creating a subshell.
Explanation:
The (IFS=":"; echo "one:two:three")
command encloses the code within parentheses to create a subshell. Inside the subshell, the IFS environment variable is changed to “:” and then the echo
command is executed to print the string “one:two:three”. The IFS value outside the subshell remains unaffected.
Example output:
one:two:three
Conclusion:
The IFS command is a powerful tool for customizing word splitting behavior in Unix shells. It allows you to change the delimiter used for word splitting and provides flexibility in processing files and data with different delimiters. Understanding and utilizing the different use cases of the IFS command can greatly enhance your shell scripting capabilities.