0

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.

jww
  • 97,681
  • 90
  • 411
  • 885
Verma
  • 13
  • 1
  • 1
  • 3
  • A little search goes a long way. Possible duplicate of [How to set a variable to the output from a command in Bash?](https://stackoverflow.com/q/4651437/608639), [How can I assign the output of a command to a shell variable?](https://unix.stackexchange.com/q/16024/56041), [Storing output of command in shell variable](https://unix.stackexchange.com/q/4569/56041), etc. – jww Apr 22 '18 at 14:19

2 Answers2

8

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)
Sébastien S.
  • 1,444
  • 8
  • 14
0

This is working for me.

#!/bin/bash 

my_command='ls | grep server.js | wc -l';

my_data=$(eval "$my_command");

echo "value in echo is:" $my_data;

if [ $my_data == "1" ]; then
    echo "value is equal to 1";
else
    echo "value is not equal to 1";
fi
M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36