Search code examples
bashechoifs

Using IFS rather than whitepace in bash


There is a quite nasty expression that want to echo using bash.

The expression is:

'one two -- 

Note: There is white space after --.

So I have:

IFS=
echo 'one$IFStwoIFS--$IFS

But the result is:

one$IFStwo$IFS--$IFS

Solution

  • You have few issues with your approach:

    1. Within single quote variables are not expanded in shell
    2. In the string one$IFStwo$IFS--$IFS first instance of $IFS will not be expanded since you have string two next to $IFS so it attempts to expand non-existent variable $IFStwo.
    3. Default value of $IFS is $' \t\n'

    You can use:

    echo "one${IFS}two$IFS--$IFS"
    

    which will expand to (cat -A output):

    one ^I$
    two ^I$
    -- ^I$