如何使 bash 脚本在新行上终止
这是出于学习目的。我编写了一个模拟打字的脚本。
用法是:
$ 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实并非如此:
;
表示命令结束。对于管道和输入/输出重定向(|
、<
、>
)以及有意义的符号,您也会遇到类似的问题。您唯一的选择是将参数放在引号中。
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.
您还可以修改脚本以从标准输入读取:
cat 命令会将用户的所有输入分配给 the_input,直到键入 ^D。
优点是用户可以输入多行并且行距
线内将被保留。
整洁的剧本!
You can also modify your script to read from stdin:
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!