Suraj Menon Suraj Menon - 1 year ago 59
Bash Question

Assigning a command output to a shell script variable

How do I assign a command output to a shell script variable.

echo ${b%?} | rev | cut -d'/' -f 1 | rev

gives me a path..for example:

The above command gives me home1 as the output. I need to assign this output to a shell script variable.

I tried the below code

c=${b%?} |rev | cut -d '/' -f 1 | rev

echo $c

But it didn't work.

Answer Source

To assign output of some command to a variable you need to use command substitution :


For your case:

c=$(echo {b%?} |rev | cut -d '/' -f 1 | rev)

Just wondering why dont you try

basename ${b} 

Or just

echo ${b##*/}

If you want to trim last number from your path than:

echo $b
c=$(echo ${b##*/})
echo ${c}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download