-1

So I am new to bash scripting in Linux. My question is how can I check if the parameter is null or not null. If it is not null it should return 0 and if it is null it should return 1 and an echo "no parameters".

My code looks like this:

#!/bin/sh
 while [ -n "$1"]; do
 echo $1
 shift 
 done
Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
private432
  • 19
  • 5
  • Does this answer your question? [Check existence of input argument in a Bash shell script](https://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script) – Vyacheslav Pukhanov Mar 18 '20 at 11:31
  • Note that `$1` can be set *and* null; a null parameter is still a parameter. You might want to use `$#` instead to see how many arguments were received. – chepner Mar 18 '20 at 11:50
  • If you're new to the shell, now is the time to create good habits. Do not use `[`. Ever. Spell it `test`. Write your script: `while test -n "$1"; do echo $1; shift; done`. They are exactly the same thing except that `[` requires that its final argument be `]`, an oddity which has caused countless hours of confusion and killed many kittens. – William Pursell Mar 18 '20 at 11:57
  • @fg1004 : Please be precise: What do you mean by being **null**? What do you mean by **returning** 0? Both tems can be interpreted in different ways. BTW, your code writes the parameters passed to your script on stdout, one per line, until it encounters an empty parameter. This solution is not really related to your question. If you ask something on SO, you should show your own attempt to solve the problem. – user1934428 Mar 18 '20 at 15:37

1 Answers1

1

When you say "should return 1" and "should return 0", is a bit confusing. Functions return values, scripts exit with return codes. I hope this helps

#!/bin/bash

if [ -z "$1" ]
then
        echo "No params given"
        exit 1
else
        echo "PARAM GIVEN:$1"
        exit 0
fi
Francesco Gasparetto
  • 1,819
  • 16
  • 20