pwp
pwp

Reputation: 161

What is wrong in this bash read -n?

I'm learning Bash and am looking at the read command. I thought the difference between the -N and the -n option was that -N would overwrite the IFS while -n wouldn't. In the following example I expected var6 to take the value of "ijfz", because I thought the space would act as field separator. But it seems to have value "ijfz e". The space wasn't used as field separator

printf "%s\n" "ijfz eszev enacht" | {
read -n 6 var6
printf "%s\n" "$var6"
}

I wanted to see what was $IFS, but the following printf command doesn't learn me too much:

printf ":%s:\n" "$IFS"

gives the following output

:   
:

What am I not understanding...?

Upvotes: 1

Views: 1237

Answers (1)

anubhava
anubhava

Reputation: 786359

By delimiter it means using option -d. See this difference:

printf "%s\n" "ijfz eszev enacht" | { read -d ' ' -N 6 var6; printf "[%s]\n" "$var6"; }
[ijfz e]

printf "%s\n" "ijfz eszev enacht" | { read -d ' ' -n 6 var6; printf "[%s]\n" "$var6"; }
[ijfz]
  1. In first case when using -N it ignores -d ' ' and reads exactly 6 characters.
  2. In second case when using -n it respects -d ' ' and reads until a space is read.

Upvotes: 3

Related Questions