0

So here's a simple script to evaluate a string length and print whether it is greater than or less than a value.

#!/bin/sh

FILENAME="thisislongerthantencharacters"
echo $FILENAME
echo "$FILENAME" | wc -c 
if [ $( "$FILENAME" | wc -c ) -gt 10 ]
    then echo "FILENAME is longer than 10 characters for: $FILENAME."

elif [ $( "$FILENAME" | wc -c ) -lt 10 ]
    then echo "FILENAME is less than 10 characters for: $FILENAME."
else
    echo "None of the above"
fi

For some reason, I only get the output that it is less than, regardless of the string length. Output:

thisislongerthantencharacters
30
FILENAME is less than 10 characters for: thisislongerthantencharacters.

May I know what I am doing wrong exactly? And why is the character count a bit off?

  • `"$FILENAME" | wc -c` _executes_ `thisislongerthantencharacters` as a command, and that probably prints nothing. Perhaps you meant `printf %s "$FILENAME" | wc -c`? But you could just use `${#FILENAME}`. – Biffen Sep 24 '21 at 06:07
  • You don't need `wc` on POSIX shells, instead use `"${#FILENAME}"`. – Jetchisel Sep 24 '21 at 06:10
  • [ShellCheck](https://www.shellcheck.net) is your friend. – Biffen Sep 24 '21 at 06:10
  • 1
    As an aside, you want to perform the length calculation just once, and then keep the result in a variable (especially if you are doing it inefficiently with an external process); or use a `case` statement which lets you use the command substitution as the expression to switch on. – tripleee Sep 24 '21 at 06:12
  • @ChrisChance Note that the top answer to the duplicate is Bash-specific (or at least not POSIX), but your shebang says `sh` (but then you also tagged the question with Bash). – Biffen Sep 24 '21 at 06:12

0 Answers0