Friday, May 27, 2022

[SOLVED] Bash script that allows one word as user input

Issue

Made a script that the user gives a "parameter" and it prints out if it is a file, directory or non of them. This is it :

    #!/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

Altough i want the user to be allowed to give only one word as a parameter. How do i make this happen ? (For example if user press space after first word there would be an error message showing "wrong input")


Solution

#!/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

See http://mywiki.wooledge.org/BashFAQ/031 for the difference between [...] and [[...]].



Answered By - Ed Morton
Answer Checked By - Mildred Charles (WPSolving Admin)