Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the length of an argument in bash?

Let's say I want to check if the first argument is 2 characters long. I tried

if [ ${#$1} -e 2]

but it doesn't work.

like image 582
bug Avatar asked Oct 26 '25 10:10

bug


1 Answers

  • Don't use $ in the parameter expansion
  • Use -eq for numerical comparison
  • Add a space before the ]:

All in all:

if [ ${#1} -eq 2 ]
then
  echo "It's two characters long"
fi
like image 71
that other guy Avatar answered Oct 29 '25 02:10

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!