mirror of
https://github.com/dylanaraps/pure-sh-bible
synced 2024-06-08 00:32:32 +02:00
FIX: read strips leading & trailing IFS whitespace
This commit is contained in:
parent
bb10d3173c
commit
601d4955f9
|
@ -410,11 +410,16 @@ Alternative to the `head` command.
|
||||||
```sh
|
```sh
|
||||||
head() {
|
head() {
|
||||||
# Usage: head "n" "file"
|
# Usage: head "n" "file"
|
||||||
|
OLDIFS="$IFS"
|
||||||
|
# `read` strips leading and trailing spaces, tabs, and newlines
|
||||||
|
# if IFS contains any of them, so clear out IFS
|
||||||
|
IFS=
|
||||||
while read -r line; do
|
while read -r line; do
|
||||||
printf '%s\n' "$line"
|
printf '%s\n' "$line"
|
||||||
i=$((i+1))
|
i=$((i+1))
|
||||||
[ "$i" = "$1" ] && return
|
[ "$i" = "$1" ] && return
|
||||||
done < "$2"
|
done < "$2"
|
||||||
|
IFS="$OLDIFS"
|
||||||
|
|
||||||
# 'read' used in a loop will skip over
|
# 'read' used in a loop will skip over
|
||||||
# the last line of a file if it does not contain
|
# the last line of a file if it does not contain
|
||||||
|
@ -647,9 +652,11 @@ done
|
||||||
## Loop over the contents of a file
|
## Loop over the contents of a file
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
|
OLDIFS="$IFS"; IFS=
|
||||||
while read -r line || [ -n "$line" ]; do
|
while read -r line || [ -n "$line" ]; do
|
||||||
printf '%s\n' "$line"
|
printf '%s\n' "$line"
|
||||||
done < "file"
|
done < "file"
|
||||||
|
IFS="$OLDIFS"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Loop over files and directories
|
## Loop over files and directories
|
||||||
|
|
Loading…
Reference in a new issue