简体   繁体   中英

IFS in bash scripting

I'm learning about IFS in Bash scripting. I'm not able to understand the IFS concept.

Consider the below file. mem.txt

i6

16GB

10T

And there is below shell script to

#!/bin/bash
echo "File pls"
read file
while read -r CPU MEM DISK; do
        echo "CPU : $CPU"
        echo "MEM : $MEM"
        echo "DISK: $DISK"
done<"$file"

I Read that ,The shell shall set IFS to space,tab,newline.So when I run the script,

File pls
mem.txt
CPU : i6
MEM : 
DISK: 
CPU : 4hz
MEM : 
DISK: 
CPU : 16GB
MEM : 
DISK: 
CPU : 10TB
MEM : 
DISK: 

Why it was not showing each entry per line, like CPU :i6 ; MEM : 16GB; Disk : 10T since IFS accepts newline delimiter as entry? Please explain how IFS works?

As the noted in the comments, read works on a line of input. So for each line of your file, you call read anew. If the input format is fixed a and you'd still need to do this, you could for for instance use sed (if reaching outside bash is OK) to group each six lines into a single line (see note bellow) of input like this:

while read -r CPU MEM DISK; do
   ...
done < <(sed -ne 'N;N;N;N;s/\n/ /gp;n' "$file")

This reads five lines of input into pattern space, replaces newlines with spaces, prints the result and discards the following line of input. Rinse and repeat.

You can also run an many reads as you have lines of input:

#!/bin/bash
echo "File pls"
read file
while { read CPU ; read blank;
        read MEM ; read blank;
        read DISK; }; do
          echo "CPU : $CPU"
          echo "MEM : $MEM"
          echo "DISK: $DISK"
          read blank  #placed it here so that file can but does not have to end
                      #with double trailing newline.
done <$file

Needless to say, neither of the two options look particularly appealing and perhaps considering different format input or non bash parsing would be a better nicer way to go.


Note, you can change new line delimiter of read with -d , but you'd still needs to change your input format to be reflective of your choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM