1
#!/bin/sh 

if test -n $1  
then  
  echo "Some input entered"  
  echo $1  
else  
  echo "no input entered"  
fi

The above code is supposed to say "no input entered" if I dont pass an argument to the shell script. the echo $1 shows a blank line when I dont pass any arguments. its saying "some input entered" even without any arguments.

2
  • [-n string] True if the string is not null Commented Aug 3, 2011 at 0:47
  • Are you deliberately trying to maintain bourne shell compatibility? Can't you use #!/bin/bash? And finally, if you're using bash, forget test and start using if [[ cond ]] ; then form of syntax. Good luck. Commented Aug 3, 2011 at 0:50

2 Answers 2

5

put quotes around your $1. Without them, the $1 just vanishes and test confusingly reports "nothing" to be not empty.

if test -n "$1" 
then
    ....
Sign up to request clarification or add additional context in comments.

Comments

1

Skip test and put quotes around the $1:

#!/bin/sh 

if [ -n "$1" ]
then  
  echo "Some input entered"  
  echo $1  
else  
  echo "no input entered"  
fi

2 Comments

[ is just a synonym for test
@evil otto - I did not know that, but now that I look at the test manpage, I see that you are correct! :) @dasman should give you the check, as you had the answer first.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.