Suraj Menon Suraj Menon - 2 months ago 6
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


${b%?}
gives me a path..for example:
/home/home1


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.

PS. PS.
Answer

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

variable=$(command)

For your case:

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

Just wondering why dont you try

basename ${b} 

Or just

echo ${b##*/}
home1

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

b="/home/home1"
echo $b
/home/home1
b=${b//[[:digit:]]/}
c=$(echo ${b##*/})
echo ${c}
home
Comments