Search code examples
linuxbashshellifs

IFS and moving through single positions in directory


I have two questions .

  1. I have found following code line in script : IFS=${IFS#??} I would like to understand what it is exactly doing ?
  2. When I am trying to perform something in every place from directory like eg.:

    $1 = home/user/bin/etc/something...
    

    so I need to change IFS to "/" and then proceed this in for loop like

    while [ -e "$1" ]; do 
        for F in `$1`
            #do something
        done
    shift
    done
    

Is that the correct way ?


Solution

  • ${var#??} is a shell parameter expansion. It tries to match the beginning of $var with the pattern written after #. If it does, it returns the variable $var with that part removed. Since ? matches any character, this means that ${var#??} removes the first two chars from the var $var.

    $ var="hello"
    $ echo ${var#??}
    llo
    

    So with IFS=${IFS#??} you are resetting IFS to its value after removing its two first chars.


    To loop through the words in a /-delimited string, you can store the splitted string into an array and then loop through it:

    $ IFS="/" read -r -a myarray <<< "home/user/bin/etc/something"
    $ for w in "${array[@]}"; do echo "-- $w"; done
    -- home
    -- user
    -- bin
    -- etc
    -- something