如何使 bash 脚本在新行上终止

发布于 2024-11-15 19:34:41 字数 764 浏览 2 评论 0原文

这是出于学习目的。我编写了一个模拟打字的脚本。

用法是:

$ typewriter (insert some text here)

然后脚本会以随机的方式回显它,看起来就像有人正在打字。很好,但问题是,如果输入包含分号 (;),则会中断。

例如:

$ typewriter hello; world

我想这是一个简单的修复。我就是想不通。

提前致谢!

代码:

#!/bin/bash
#Displays input as if someone were typing it

RANGE=4
the_input=$*
if [ x$* = "x" ] || [ x$* = "xusage" ] || [ x$* = "xhelp" ] || [ x$* = "x--help" ];
then
        echo "Usage: typewriter <some text that you want to look like it's typed>"
        exit 1

fi
  while [ -n "$the_input" ]
  do
    number=$RANDOM
    let "number %= RANGE"
    printf "%c" "$the_input"
    sleep .$number
    the_input=${the_input#?}
  done
  printf "\n"

This is for learning purposes. I wrote a script that will simulate typing.

The usage is:

$ typewriter (insert some text here)

Then the script will echo it in a random way that looks like someone is typing. Fine, but the problem is, if the input includes a semicolon ( ; ) it breaks.

For instance:

$ typewriter hello; world

I imagine this is a simple fix. I just cannot figure it out.

Thanks in advance!

CODE:

#!/bin/bash
#Displays input as if someone were typing it

RANGE=4
the_input=$*
if [ x$* = "x" ] || [ x$* = "xusage" ] || [ x$* = "xhelp" ] || [ x$* = "x--help" ];
then
        echo "Usage: typewriter <some text that you want to look like it's typed>"
        exit 1

fi
  while [ -n "$the_input" ]
  do
    number=$RANDOM
    let "number %= RANGE"
    printf "%c" "$the_input"
    sleep .$number
    the_input=${the_input#?}
  done
  printf "\n"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等数载,海棠开 2024-11-22 19:34:41

事实并非如此: ; 表示命令结束。对于管道和输入/输出重定向(|<>)以及有意义的符号,您也会遇到类似的问题。

您唯一的选择是将参数放在引号中。

typewriter "some; text<>| that should be displayed"

Not really: ; signals the end of the command. You'll have a similar issue with pipes and input/output redirection (|, <, >), symbols that have meaning.

Your only alternative is to put the argument in quotes.

typewriter "some; text<>| that should be displayed"
記柔刀 2024-11-22 19:34:41

您还可以修改脚本以从标准输入读取:

the_input=`cat`

cat 命令会将用户的所有输入分配给 the_input,直到键入 ^D。

优点是用户可以输入多行并且行距
线内将被保留。

整洁的剧本!

You can also modify your script to read from stdin:

the_input=`cat`

The cat command will assign to the_input all the input from the user until a ^D is typed.

The advantages are that the user can type more than one line and the spacing
within the line will be preserved.

Neat script!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文