How do I assign the output of a command to a variable within a loop in bash?

In the else of the main if condition .

else
       set lnk = $(readlink -f <path> | cut -d '/' -f7)
        echo "$lnk" 
        if [[ "$lnk" == "$ver" ]]

When I run the above on command line , the execution seems to be fine and I get the desired output. But when I try to assign it to a variable within a loop , it doesnt get assigned.Hence the "if condition" after the variable assignment doesnt get evaluated.

Os Version : RHEL 6.0

Run the script with set -x and see what comes out.

The output suggests the same thing which I mentioned in my problem statement.

++ readlink -f <host>:<sym lnk>
++ cut -d / -f7
+ set lnk =
+ echo

Doesnt seem to be assigning anything in the loop to the variable lnk.

A bit difficult to believe. In bash , set is not used to assign variables, be it interactively or in a script. Simply drop it. And, remove the spaces around the = sign.

lnk="$(readlink -f <path> | cut -d '/' -f7)"

Thanks admins.. I had actually tried that but still no luck .

lnk="$(readlink -f <path> | cut -d '/' -f7)"
echo "$lnk"

Output

++ readlink -f <path>
++ cut -d / -f7
+ lnk=
+ echo ''

--- Post updated at 01:13 PM ---

I actually meant ran the below on command line to get the desired output.

readlink -f <path> | cut -d '/' -f7

What does <path> stand for? Does the readlink result have 7+ / separated fields?

<path> = path to the symbolic link.
-f7 = relates to the version which is 7th field in the above path.

The output of the command is 1.0.1

By "within a loop" do you happen to mean "behind a pipe?" also known as "inside a subshell"? That will not work. Variables inside a subshell do not get communicated to outside the subshell.

In which case is there a possibility to evaluate the output of the command to another variable.
eg.

if ( $(readlink -f <path> | cut -d '/' -f7)" == "$ver"); then

Please show us your entire script instead of showing us one line at a time.

It seems highly likely that you are setting the variable you want inside a sub-shell and that makes the assigned value invisible outside of that sub-shell. But we can't know that until we can see all of your code.

2 Likes

I think the main problem is shown in post#3: the

readlink -f <path> | cut -d / -f 7

gives an empty string.
(A subshell and/or a wrong assignment would cause additional problems of course.)
If the question is for a better debugging, then I suggest to repeat the readlink -f <path> command without a following pipe. Maybe framed by some "debug" text:

echo "debug: -->$(readlink -f <path>)<--" 

If your loop is behind a pipe, that would mean stuffing your entire loop inside $( ). Or storing the result in a temporary file.

This is just guessing though. This is a really common problem which we can't rule out without seeing more of your code.

1 Like