this post was submitted on 17 Feb 2025
6 points (87.5% liked)

Bash

812 readers
1 users here now

Talk about the Bash Shell and Bash scripting

founded 4 years ago
MODERATORS
 

why I can't pass my input in foo function

foo() {
	read -r -p "delete $name (default is no) [y/n]?  " choice
	choice="${choice:-n}"
	echo "\$choice: $choice"
}

printf "%s\n" "foo" "bar" "baz" "eggs" "spam" | while read -r name; do
	foo

Expected result:

delete foo (default is no) [y/n]? USER_INPUT
$choice: USER_INPUT
delete bar (default is no) [y/n]? USER_INPUT
$choice: USER_INPUT
# truncated

Actual output:

$choice: bar
$choice: eggs
$choice: n

[!NOTE] Actual output produced without user interaction

you are viewing a single comment's thread
view the rest of the comments
[โ€“] korthrun 4 points 2 days ago (1 children)

Wild, I get syntax error: unexpected end of file when I run your code, so just that alone is very confusing.

When you're inside foo here, STDIN is the pipe. Once I fix this syntax error that you somehow dodge and add some extra debugging, you can get a better picture of what's going on here:

foo() {
        read -r -p "delete $name (default is no) [y/n]?  " choice
        choice="${choice:-n}"
        echo "\$choice: $choice"
}

printf "%s\n" "foo" "bar" "baz" "eggs" "spam" | while read -r name; do
        printf "Got name '%s'\n" "$name"
        echo calling foo
        foo
done
Got name 'foo'
calling foo
$choice: bar
Got name 'baz'
calling foo
$choice: eggs
Got name 'spam'
calling foo
$choice: n
[โ€“] e55am@programming.dev 3 points 2 days ago

Sorry, I've dropped done by mistake when I pasted my snippet.

And thanks for your explanation, but I didn't fully understand how this happened.