4

如何在 bash shell 中从键盘查找用户输入?我在想这会行得通,

int b;

scanf("%d", &b);

但它说

-bash:/Users/[name]/.bash_profile:第 17 行:意外标记 `"%d",' 附近的语法错误

-bash:/Users/[name]/.bash_profile:第 17 行:`scanf("%d", &b);'

编辑

backdoor() {
   printf "\nAccess backdoor Mr. Fletcher?\n\n"
   read -r b
   if (( b == 1 )) ; then
     printf "\nAccessing backdoor...\n\n"
   fi   
}
4

3 回答 3

7

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

于 2012-05-22T00:14:54.153 回答
2

虽然您可以在 Bash 中将变量声明为整数,但结果不会如您所愿。非整数值将被转换为零,这可能不是您想要的。这是确保您收集整数的更安全的方法:

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

当您想告知用户为什么拒绝某个值,而不仅仅是重新提示时,这尤其有用。

于 2012-05-22T00:19:29.337 回答
0

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
}
于 2012-05-22T00:32:16.400 回答