Tuesday, November 16, 2021

[SOLVED] Positional parameter not readable inside the variable - bash script

Issue

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

Solution

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


Answered By - William Pursell