0

I have a problem with the small script I am working on, can you please explain why is this not working:

#!/bin/bash
var1=$( linux command to list ldap users | grep "user: $1")
echo $var1

So, when I deploy my script ( ./mycript.sh $michael ), it should use that value instead of $1 and provide the output via echo $variable1? In my case that is not working.

Can you please explain how should I configure positional parameter inside the variable?

I tried the this solution, but that did not help:

#!/bin/bash
var1=$( linux command to list ldap users | grep user: $1)
echo $var1
Belphegor
  • 49
  • 5
  • 1
    Well, `var1` is not `variable1`. `In my case that is not working.` Debug the script. Run the script with `set -x` and confirm your asumptions. `$michael ), it should use that value instead of $1` What value? Is `michael` variable set in the parent process? `I tried the this solution, but that did not help:` But what did it result in? Did you get a message from `grep` that there is no such file? Most probably, `$michael` variable is empty. – KamilCuk Sep 23 '21 at 14:15
  • Thank you for the fast reply, that was a typo, it is var1 – Belphegor Sep 23 '21 at 14:18
  • What is the value of `$michael` in the invoking shell? Perhaps you meant `./myscript.sh michael` – William Pursell Sep 23 '21 at 14:20
  • You guys saved my day! I used ./myscript.sh $michael instead of using ./myscript.sh michael that is why there was no output. I used this command many times before, but today I got stuck and I thought that the problem is with the script, not with the actual input, thus $michael does not exist, but michael does and it is working now! I can study further without having this in my mind, thank you very much! – Belphegor Sep 23 '21 at 14:28

1 Answers1

0

If you invoke your script as ./mycript.sh $michael and the variable michael is not set in the shell, they you are calling your script with no arguments. Perhaps you meant ./myscript.h michael to pass the literal string michael as the first argument. A good way to protect against this sort of error in your script is to write:

#!/bin/bash
var1=$( linux command to list ldap users | grep "user: ${1:?}")
echo "$var1"

The ${1:?} will expand to $1 if that parameter is non-empty. If it is empty, you'll get an error message.

If you'd like the script to terminate if no values are found by grep, you might want:

var1=$( linux command to list ldap users | grep "user: ${1:?}") || exit

But it's probably easier/better to actually validate the arguments and print an error message. (Personally, I find the error message from ${:?} constructs to bit less than ideal.) Something like:

#!/bin/bash
if test $# -lt 1; then echo 'Missing arguments' >&2; exit 1; fi
William Pursell
  • 204,365
  • 48
  • 270
  • 300