允许一个单词作为用户输入的Bash脚本



制作一个脚本,用户给出一个"参数";然后打印出它是文件、目录还是非文件。

#!/bin/bash
read parametros
for filename in *
do
if [ -f "$parametros" ];
then
echo "$parametros is a file"
elif [ -d "$parametros" ];
then
echo "$parametros is a directory"
else
echo " There is not such file or directory"
fi
exit
done

虽然我希望允许用户只提供一个单词作为参数。我该怎么做呢?(例如,如果用户在第一个单词后按空格键,就会出现"输入错误"的错误信息)

#!/bin/bash
read parametros
if [[ "$parametros" = *[[:space:]]* ]]
then
echo "wrong input"
elif [[ -f "$parametros" ]]
then
echo "$parametros is a file"
elif [[ -d "$parametros" ]]
then
echo "$parametros is a directory"
else
echo " There is not such file or directory"
fi

[...][[...]]的区别见http://mywiki.wooledge.org/BashFAQ/031

你必须使用$#。它给出了参数的个数。代码类似于:

if [ "$#" -ne 1 ]; then
printf 'ERROR!n'
exit 1
fi

首先,我很好奇为什么要限制为一个单词-文件或目录中可以有空格,但可能您在上下文中以某种方式阻止了这一点。

这里有一些你可以做到的方法:

  1. 输入后验证输入-检查是否有空格,例如:if [[ "parametros" == *" " ]]; then...
  2. 在while循环中一次获取一个字符,例如使用:read -n1 char
    • 如果是空格则显示错误
    • 如果输入'enter'则中断循环
    • 从输入的字符
    • 构建整个字符串

1显然要简单得多,但也许为了获得您所希望的即时反馈,2值得您花些功夫?

最新更新