scanf equivalent for Bash? scanf equivalent for Bash? bash bash

scanf equivalent for Bash?


Just use the read builtin:

read -r b

No need to specify type (as per %d), as variables aren't typed in shell scripts unless you jump through (needless) hoops to make them so; if you want to use a value as a decimal, that's a question of the context in which it's evaluated, not the manner in which it's read or stored.

For instance:

(( b == 1 ))

...treats $b as a decimal, whereas

[[ $b = 1 ]]

...does a string comparison between b and "1".


While you can declare variables as integers in Bash, the results won't do what you expect. A non-integer value will be converted to zero, which is probably not what you want. Here is a more bullet-proof way to ensure you gather an integer:

while read -p "Enter integer: " integer; do    [[ "$integer" =~ [[:digit:]]+ ]] && break    echo "Not an integer: $integer" >&2done

This is particularly useful when you want to inform the user why a value is rejected, rather than just re-prompting.


You're trying to mix C-like syntax with Bash syntax.

backdoor() {    printf '\n%s\n\n' 'Access backdoor Mr. Fletcher?'    read -r b    if ((b == 1))    then        printf '\n%s\n\n' 'Accessing backdoor...'    fi}