相当于 Bash 的 scanf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10694224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scanf equivalent for Bash?
提问by Nightlock32
How do I look for user input from the keyboard in the bash shell? I was thinking this would just work,
如何在 bash shell 中从键盘查找用户输入?我以为这会奏效,
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);'
-bash: /Users/[name]/.bash_profile: line 17: 意外标记附近的语法错误`"%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
}
回答by Charles Duffy
Just use the read
builtin:
只需使用read
内置:
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.
无需指定类型(根据%d
),因为变量不会在 shell 脚本中输入,除非您跳过(不必要的)箍使它们如此;如果您想使用一个值作为小数,那是一个评估它的上下文的问题,而不是它的读取或存储方式的问题。
For instance:
例如:
(( b == 1 ))
...treats $b
as a decimal, whereas
...视为$b
小数,而
[[ $b = 1 ]]
...does a string comparisonbetween b and "1"
.
...在 b 和 之间进行字符串比较"1"
。
回答by Todd A. Jacobs
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:
虽然您可以在 Bash 中将变量声明为整数,但结果不会如您所愿。非整数值将被转换为零,这可能不是您想要的。这是确保您收集整数的更安全的方法:
while read -p "Enter integer: " integer; do
[[ "$integer" =~ [[:digit:]]+ ]] && break
echo "Not an integer: $integer" >&2
done
This is particularly useful when you want to inform the user whya value is rejected, rather than just re-prompting.
当您想通知用户拒绝某个值的原因而不只是重新提示时,这尤其有用。
回答by Paused until further notice.
You're trying to mix C-like syntax with Bash syntax.
您正在尝试将类 C 语法与 Bash 语法混合使用。
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
}