Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the below condition where values are as below.
```
emp_name="Sid"
emp_id=1234
emp_hobby=""
emp_likes="swimming"
emp_dislikes=""

emp_summary="emp_name:$emp_name,emp_id:$emp_id,emp_hobby:$emp_hobby,emp_likes:$emp_likes,emp_dislikes:$emp_dislikes"
```

if I echo above with the values that are provided as an example it will give result as

`"emp_name:"Sid",emp_id:1234,emp_hobby:,empf_likes:"swimming",emp_dislikes:"`

I need help with a dynamic code where if any of the value is null that complete variable is removed from the echo as below

`"emp_name:"Sid",emp_id:1234,emp_likes:"swimming"`

i tried {parameter:+word} returns the values but not sure how to deal with the variable name itself.

What I have tried:

i tried {parameter:+word} returns the values but not sure how to deal with the variable name itself.
Posted
Updated 17-Jul-23 21:55pm

1 solution

Shell
cat script #bash script

emp_name="Sid"
emp_id=1234
emp_hobby=""
emp_likes="swimming"
emp_dislikes=""

emp_summary=""
summary=""

 #
 # if the names are not known ..._ 
 # then use something like
 #      for var in $(compgen -v|grep ^emp_)

for var in emp_name emp_id emp_hobby emp_likes emp_dislikes
do
	# use indirect variable' capability of bash - aka namerefs
	declare -n namref=$var;
	
	[ "" != "$namref" ] && summary+="${!namref}:$namref,"
done

emp_summary="${summary/%,/}" #trim the last comma off the final result

echo "emp_summary:${emp_summary}"

 #test run
./script 
emp_summary:emp_name:Sid,emp_id:1234,emp_likes:swimming
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900