1

I use the following command to get the output (number tagged in the latest file):

 ls -lrt | tail -n1 |  awk -F'.' '{print $4}' | grep -o '[0-9]\+'

but when I use the same command in a shell script and get the result in a variable c, I don't get the proper result.

My script:

#! /bin/sh

c=ls -lrt | tail -n1 |  awk -F'.' '{print $4}' | grep -o '[0-9]\+'
echo $c

The error that shows when I execute is:

 -lrt: command not found
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Niladri Dey
  • 85
  • 1
  • 10
  • Does this answer your question? [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – Benjamin W. May 26 '20 at 12:38

1 Answers1

1

What you are doing: trying to run a command with a per-command variable.

VAR=foo ./somecommand.sh

would run ./somecommand.sh with VAR set to foo. But VAR would not be set for commands executed later.

Your example sets c=ls and tries to run -lrt - obviously this is neither found nor intended.

I assume you want to save the output to variable c.

You would use

c=`ls -lrt | tail -n1 | awk -F'.' '{print $4}' | grep -o '[0-9]+'`
echo "$c"

Modern shells use $(...) instead of `...` for command substitution, as nesting command substitution gets easier with this syntax.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
user3188140
  • 265
  • 1
  • 5