linuxshellcommand-substitution

storing the output of ls command in a shell variable


I am using below command to find a most recent file with name "candump"

ls *.log | grep "candump" | tail -n 1

The output is "candump-2018-04-19_131908.log"

I want to store the output filename to a variable in my shell script. I am using the below commands:

logfile = `ls *.log | grep "candump" | tail -n 1`

and

logfile = $(ls *.log | grep "candump" | tail -n 1)

However, both times I am getting the same error, "logfile: command not found". Am I doing something wrong? Any help is appreciated.


Solution

  • You have to stick the variable name and its value (no space before and after the =).

    Try :

    logfile=$(ls *.log | grep "candump" | tail -n 1)