Search code examples
linuxbashvariablescommandcut

How to bring the output of a cut-command into a variable?


This is a question for a Linux bash-shell-script.

I would like to bring the output of a "cut-command" into a variable. But it does not work. The variable remains empty.

Here is what I did:

MyName@MyName:~
$ fixedFilePath=aa.zz
MyName@MyName:~
$ echo $fixedFilePath
aa.zz
MyName@MyName:~
$ EP=$fixedFilePath | rev | cut -d '.' -f 1 | rev
MyName@MyName:~
$ echo $EP

MyName@MyName:~
$ 

As you can see: Nothing is in the variable $EP now. My expectation was, that in $EP is now "zz".


Solution

  • When you assign to EP, the first section, $fixedFilePath leaves nothing on stdout for the pipe to take. What it does is executes the contents of that variable. You need to echo.

    echo $fixedFilePath | rev | cut -d '.' -f 1 | rev

    Now to capture that output you need to execute it as part of the assignment. There are various ways to go about this but what I found worked in your case was surrounding it in backticks:

    EP=`echo $fixedFilePath | rev | cut -d '.' -f 1 | rev`