Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf equivalent for Bash?

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   
}
like image 642
Nightlock32 Avatar asked Jan 16 '23 15:01

Nightlock32


1 Answers

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

like image 184
Charles Duffy Avatar answered Jan 25 '23 07:01

Charles Duffy