How can I read a variable in bash, with the type specified like in C's scanf?

bash, scanf, terminal

Solution

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"`.

Problem

How do I look for user input from the keyboard in the bash shell? I was thinking this would just work, ``` int b; scanf("%d", &b); ``` but it says -bash: /Users/[name]/.bash_profile: line 17: syntax error near unexpected token `"%d",' -bash: /Users/[name]/.bash_profile: line 17: `scanf("%d", &b);' EDIT ``` backdoor() { printf "\nAccess backdoor Mr. Fletcher?\n\n" read -r b if (( b == 1 )) ; then printf "\nAccessing backdoor...\n\n" fi } ```

Original source