I would like to know how I can do to restrict the type of file that it receives as a parameter, that is, how can I do so that if it is not a .txt file that is entered, the program ends.
Here is what I have so far:
#!/bin/bash
if test "$1" = "" ; then
echo "Hay que introducir un argumento que sea un archivo de texto para poder ejecutar este guión"
exit 1
else
if [ -f "$1" ]; then
echo "El fichero sí existe."
cuenta=$(cat "$1" | wc -m)
echo Hay $cuenta palabras en $1
else
echo "El argumento no es un fichero"
exit 2
fi
fi
To run the script I do the following:
$ chmod 777 cuatro.sh
$ ./cuatro.sh
If you just want to look at the file extension you can use a regular expression:
I think your question was:
how can i do to restrict the file type
If you just look at the extension , you can receive any renamed file that isn't a text file...
You can do something similar to this:
You can also "review" other types of files... You can see the complete list with:
Simply extract the extension from the file and then look at its value:
I am using comparison here
[
instead of[[
, since the latter is unique to Bash and the former is more generic as it is defined by POSIX .If you want a simple way you can use the file command
Example (I have 2 files)
First:
The second:
If I make a 'file' on them I get: