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
    – anubhava
    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.
    – chepner
    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.

7
  • Perfect dear, works like charm, now except Java, bash would walk on my nerve too :D, thanks.
    – user2889419
    Commented Aug 7, 2014 at 21:11
  • is there any other better way(correct way) to find out if any argument is provided or not except '${#1}' approach?
    – user2889419
    Commented Aug 7, 2014 at 21:14
  • 1
    ...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. Commented Aug 7, 2014 at 21:14
  • 3
    @user2889419, ...in baseline POSIX sh, [ ${#1} -eq 0 ] is better written as [ -z "$1" ]. Commented Aug 7, 2014 at 21:18
  • 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. Commented Aug 7, 2014 at 22:51