在csh Shell脚本中读取带有空格的用户输入
我有一个脚本,用户应该能够输入带空格的字符串。 到目前为止,我已经:
#bin/csh
echo "TEST 1"
echo -n "Input : "
set TEST = $<
echo "Var | " $TEST
set TEST=`echo $TEST`
echo "Var after echo | " $TEST
set TEST=`echo $TEST | sed 's/ /_/g'`
echo "Var after change | " $TEST
如果我在“input”处输入字符串“rr r”,$TEST 将只接受“r”。 我希望能够将 $TEST 设置为“rr r”。 这可能吗? 如果我输入像“1 1 1”这样的字符串,我会收到错误:
set:变量名必须以a开头 信。
这是什么原因呢?
I have a script where the user should be able to enter a string with spaces. So far I have:
#bin/csh
echo "TEST 1"
echo -n "Input : "
set TEST = lt;
echo "Var | " $TEST
set TEST=`echo $TEST`
echo "Var after echo | " $TEST
set TEST=`echo $TEST | sed 's/ /_/g'`
echo "Var after change | " $TEST
If I enter the string "r r r" at "input", $TEST would only take "r". I want to be able to set $TEST to "r r r". Is this possible?
If I enter a string like "1 1 1" I get an error:
set: Variable name must begin with a
letter.
What's the reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您没有在
SET
语句中使用引号。 当您输入"rr r"
作为输入时,两种不同的变体(不带引号和带引号)等效于:第一个只是将
TEST
设置为" r"
和r
到""
(两次!)。 第二个将TEST
设置为"rr r"
。 这是因为csh
允许您执行多项赋值,例如:因此您需要使用
SET
的带引号的变体。 检查以下记录以了解其工作原理:您收到输入
"1 1 1"
所描述的错误的原因是因为您正在有效执行:和
csh 认为这意味着您要创建设置为
"1"
的变量TEST
,后跟变量1
,这不会t 以字母开头,因此不允许。 使用引用的变体,这将变为:它将执行您所期望的操作。
It's because you're not using quotes in your
SET
statement. When you enter"r r r"
as your input, the two different variants (unquoted and quoted) are equivalent to:The first of those simply sets
TEST
to"r"
andr
to""
(twice!). The second setsTEST
to"r r r"
. That's becausecsh
lets you do multiple assignments like:So you need to use the quoted variant of
SET
. Examine the following transcript to see how it works:The reason you're getting the error you describe with input of
"1 1 1"
is because you're effectively executing:and
csh
is taking this to mean that you want to create the variableTEST
set to"1"
followed by the variable1
, which doesn't start with a letter, hence not allowed. With the quoted variant, this becomes:which will do what you expect.