Chr*_*chs 3 linux bash shell sh ubuntu-12.04
我有以下情况:
#!/bin/bash
echo "Please enter a word:"
read foobar
Run Code Online (Sandbox Code Playgroud)
该脚本sh script.sh
在Ubuntu终端中被调用。
在互联网上搜索我发现的解决方案:
foobar=${foobar,,}
echo $foobar
Run Code Online (Sandbox Code Playgroud)
上面的方法仅适用于,bash script.sh
因此我继续研究并发现:
echo $foobar | tr '[:upper:]' '[:lower:]'
Run Code Online (Sandbox Code Playgroud)
确实对bash
和和都有效sh
,但是没有回声就不起作用。
它还将读取的输入打印两次,而不是这样打印:
Y
y
因此,如何在sh
不打印两次读取输入的情况下执行此操作?
可能是因为您尚未将转换后的输出分配给变量。另外,我建议用双引号引起来的变量,以防止单词分裂和路径名扩展。
foobar=$(echo "$foobar" | tr '[:upper:]' '[:lower:]')
Run Code Online (Sandbox Code Playgroud)
如果使用的是case
,您只需要检查输入是否为正y
或Y
负两种方式,就可以使用这样的全局模式。无需将其音译为小写形式。
case $foobar in
[yY])
echo "User said yes."
;;
*)
echo "User said no."
;;
esac
Run Code Online (Sandbox Code Playgroud)
另外,您还可以使用-s抑制显示用户输入:
read -s foobar
Run Code Online (Sandbox Code Playgroud)
总体而言,要使代码在这两种代码中都能正常工作bash
,sh
您应该已经删除了bash特定的部分:
#!/bin/bash
echo "Please enter a word:"
read -s foobar
foobar=$(echo "$foobar" | tr '[:upper:]' '[:lower:]')
echo "$foobar"
Run Code Online (Sandbox Code Playgroud)
如果只是显示较小的表格,则可以跳过分配。但是,请勿同时使用其他回声:
#!/bin/bash
echo "Please enter a word:"
read -s foobar
echo "$foobar" | tr '[:upper:]' '[:lower:]'
Run Code Online (Sandbox Code Playgroud)
的另一种替代形式case
。这是为了与POSIX兼容。
if [ "$foobar" = y ] || [ "$foobar" = Y ]; then
echo "User said yes."
else
echo "User said no."
fi
Run Code Online (Sandbox Code Playgroud)
在bash中可能就是这样。即使在不支持该${parameter,,}
功能的早期版本中也可以使用。
if [[ $foobar == [yY] ]]; then
echo "User said yes."
else
echo "User said no."
fi
Run Code Online (Sandbox Code Playgroud)