0

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.

GMichael
  • 2,726
  • 1
  • 20
  • 30

2 Answers2

2

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
P....
  • 17,421
  • 2
  • 32
  • 52
0

Just like this:

variable=`command`
Anton Malyshev
  • 8,686
  • 2
  • 27
  • 45
  • 1
    Nesting is difficult by using `backticks` – P.... Sep 22 '16 at 05:35
  • Should have no problem with c=\`${b%?} |rev | cut -d '/' -f 1 | rev\` – Anton Malyshev Sep 22 '16 at 05:39
  • 2
    Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. In particular, it's probably worth mentioning why `$(...)` is superior to `\`...\``. – Toby Speight Sep 23 '16 at 12:42