I'm trying to understand how to work with the shell variable IFS
. I have the following code:
#!/bin/bash
ourpath=$PATH
oldIFS=$IFS
IFS=":"
echo "ourpath = $ourpath"
for directory in "$ourpath"; do
echo "directory = $directory"
done
IFS=$oldIFS
Running this using bash test.sh
yields:
ourpath = ~/bin:/home/<user>/anaconda3/bin:/home/<user>/.local/bin:/home/<user>/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:~/scripts
directory = ~/bin:/home/<user>/anaconda3/bin:/home/<user>/.local/bin:/home/<user>/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:~/scripts
But I would expect directory
to loop over the directories in $PATH
because it should be split by :
. What is going wrong here?
It's the exact same as with space: You have quoted $ourpath
and it doesn't get split. If you remove the quotes then it will give you the result you're looking for.
I.e:
for directory in $ourpath ; do
echo "directory = $directory"
done
Bonus points: It won't matter if $ourpath
contains spaces because IFS
is :
, so it will only be split over :
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments