1
read user input problem (programming.dev)
submitted 5 months ago by [email protected] to c/[email protected]

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

top 1 comments
sorted by: hot top new old
[-] [email protected] 1 points 5 days ago* (last edited 5 days ago)

Do this instead to treat name as a locally scoped variable:

foo() {
    local name="$1"
    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 "$name"
done
this post was submitted on 17 Feb 2025
1 points (100.0% liked)

Bash

946 readers
1 users here now

Talk about the Bash Shell and Bash scripting

founded 5 years ago
MODERATORS