0

Dude, so sorry about the absolute noob question.
What is the problem with the following code?
I like to have a simple script which says MEH! when there is no input arg, otherwise prints it.

#!/bin/bash
if [${#$1}==0] then
echo "MEH!";
else
echo $1;
fi

OS says the line 4 has a error (unexpected token else at line 4).
So sorry dude.
Thanks in advance.

3
  • Instead of if [${#$1}==0] then use if [ $# -eq 0 ]; then Commented Aug 7, 2014 at 21:06
  • FYI, this is covered on mywiki.wooledge.org/BashPitfalls Commented Aug 7, 2014 at 21:13
  • Please read the bash man page. It is quite clear about where whitespace is required and where it is forbidden. Commented Aug 7, 2014 at 21:16

1 Answer 1

3

You probably wanted to use:

#!/bin/bash

if [ ${#1} -eq 0 ]; then
   echo "MEH!";
else
   echo $1
fi

Problems in your current if [${#$1}==0] then condition:


In general, if you want to check if your script is receiving at least a parameter, you'd better do:

if [ $# -ge 1 ]; then
   echo "$# parameters given"
else
   echo "no parameters given"
fi

or also, as commented by Charles Duffy:

if [ -z "$1" ]   # true if the variable $1 has length 0

Last and not least: check the comments below, as good information was provided.

Sign up to request clarification or add additional context in comments.

7 Comments

Perfect dear, works like charm, now except Java, bash would walk on my nerve too :D, thanks.
is there any other better way(correct way) to find out if any argument is provided or not except '${#1}' approach?
...well, in baseline POSIX [ ] as opposed to [[ ]], == isn't valid string comparison either; it's just that many shells support it as an extension. Better to use =, though.
@user2889419, ...in baseline POSIX sh, [ ${#1} -eq 0 ] is better written as [ -z "$1" ].
The problem with [ ${#1} -eq 0 ] occurs when the shell is invoked without any arguments. In that case the positional parameter 1 is not defined. While the length of an undefined variable defaults to 0, this isn't the recommended way to test -- it is a hack.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.