在 bash 和 csh 中读取用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14185180/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:10:53  来源:igfitidea点击:

Read user input in both bash and csh

bashcsh

提问by user1657743

I'm trying to create a script to to do simple things. I need to prompt the user to reply to a question, typing yes or no. The script is written for csh, but does not work when default user shell is bash. My environment is Red Hat Enterprise Linux 5

我正在尝试创建一个脚本来做简单的事情。我需要提示用户回答问题,输入是或否。该脚本是为 csh 编写的,但在默认用户 shell 是 bash 时不起作用。我的环境是 Red Hat Enterprise Linux 5

#!/bin/csh -f
echo -n Type yes to continue
set answer = $<
#...

This code works fine with csh but not with bash where it prints the following error:

此代码适用于 csh,但不适用于 bash,它会打印以下错误:

syntax error near unexpected token 'newline'
bash 'set answer =$<'

I really need to have the same script working for both shell (I thought it was the purpose of putting #!/bin/cshat the beginning of the file!)

我真的需要为两个 shell 使用相同的脚本(我认为这是放在#!/bin/csh文件开头的目的!)

I don't really know how to modify my script to make it working in bash. Could you help me please? Thanks a lot for your help.

我真的不知道如何修改我的脚本以使其在 bash 中工作。请问你能帮帮我吗?非常感谢你的帮助。

回答by cdarke

It would be hard to think of two more different shells than csh and bash. They are different languages, you cannot expect csh code to work in bash, or the other way around.

很难想到比 csh 和 bash 更多种不同的 shell。它们是不同的语言,您不能期望 csh 代码在 bash 中工作,或者相反。

In bash you read from STDIN using the shell builtin read, in csh you use the construct $<. Different languages.

在 bash 中,您使用内置的 shell 从 STDIN 读取read,在 csh 中使用构造$<。不同的语言。

I really need to have the same script working for both shellWhy? When you place #!/bin/cshat the start of the script then it will run the c-shell, use #!/bin/bashthen it will run bash. Common mistake is to have white-space or some other character before the #!, they must be absolutely the very first two bytes in the file.

我真的需要为两个 shell 使用相同的脚本为什么?当您放置#!/bin/csh在脚本的开头时,它将运行 c-shell,#!/bin/bash然后使用它将运行 bash。常见的错误是在 之前有空格或其他一些字符#!,它们必须绝对是文件中的前两个字节。