Test length of string in file
5,646
You can get string length of the variable by using ${#variable}
. And you should use -gt
instead of >
in the [
]
expression.
#!/bin/bash -
pass=$(cat < "$1") || exit
if [ "${#pass}" -gt 32 ]; then
echo >&2 "Error: Password length invalid"
exit 1
else
echo "okay"
fi
That counts the number of characters (interpreted in the current locale's encoding), not bytes, in the file passed as first argument except for the trailing newline characters, so for a file containing one line of text, that gives you the number of characters in that line.
Related videos on Youtube
Comments
-
Avinash Prabhakar over 1 year
I am not sure if I am using my argument correctly. I would like to pass in a argument which is a text file containing a string. When I run this script, it always enters the if statement even when the the number of characters of the string is below 32.
#!/bin/bash if [ {$1} > 32 ]; then echo "Error: Password length invalid" else echo "okay" fi
-
Avinash Prabhakar over 8 yearsThis works with file as the argument. Thank you very much. I can't up vote your answer as I do not have enough reputation. Sorry about that.
-
Stéphane Chazelas over 6 yearsThat gives you a number of bytes, not characters though. And it does include the line delimiter. That also assumes the GNU implementation of
stat
. For symlinks, it gives you the size of the symlink instead of the size of the data in the file pointed to by the symlink.