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.

1 Answers1

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.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Perfect dear, works like charm, now except Java, bash would walk on my nerve too :D, thanks. –  Aug 07 '14 at 21:11
  • is there any other better way(correct way) to find out if any argument is provided or not except '${#1}' approach? –  Aug 07 '14 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. – Charles Duffy Aug 07 '14 at 21:14
  • @user2889419, if your script starts with `#!/bin/bash`, `(( $# > 0 ))` to tell if it's more than zero arguments, or `[[ $1 ]]` to check if the first argument is non-empty. What do you want to do if it's explicitly provided, but empty? To provide a concrete example: if someone runs `your_script ""`, the argument exists, but is an empty string. – Charles Duffy Aug 07 '14 at 21:15
  • 3
    @user2889419, ...in baseline POSIX sh, `[ ${#1} -eq 0 ]` is better written as `[ -z "$1" ]`. – Charles Duffy Aug 07 '14 at 21:18
  • @user2889419 yes, moreover to what Charles Duffy suggest you can also use `[ $# -ge 1 ]`. – fedorqui Aug 07 '14 at 21:19
  • 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. – David C. Rankin Aug 07 '14 at 22:51