背景是这样的:
一个脚本需要用户输入用户名:
$ cat test.sh
#!/bin/bash
echo "Enter user name :\c"
read USERNAME
echo "Username ${USERNAME} received."
希望的结果是,显示完"Enter user name :"之后,光标停留在当前行,等待用户输入,可时间情况是,shell把"\c"解释成了普通字符,然后自然就换行了:
$ bash test.sh
Enter user name :\c
Tom
Username Tom received.
查了一下,echo有命令行选项:
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes (default)
缺省情况下就是不展开"\c"的,所以必须显式的指定"-e",又由于echo命令在脚本里面大量使用了,不想每一个地方去改变,所以想到定义一个alias:
#!/bin/bash
alias echo="echo -e"
echo "Enter user name :\c"
read USERNAME
echo "Username ${USERNAME} received."
测试发现行为并没有发生改变,还是没有展开解析"\c"。
接着查发现有这个一个说法:
Note: aliases are not expanded by default in non-interactive shell, and it can be enabled by setting the expand_aliases shell option using shopt.
https://www.unix.com/shell-programming-and-scripting/210897-alias-has-no-effect-script.html
原来如此。
最后脚本改成:
#!/bin/bash
shopt -s expand_aliases
alias echo="echo -e"
echo "Enter user name :\c"
read USERNAME
echo "Username ${USERNAME} received."
此时解决了我们的问题:
$ bash test.sh
Enter user name :Tom
Username Tom received.
网友评论