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
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.