Ksh save command result to variable
The problem you are running into is that the command must be surrounded by back ticks, not single quotes. This is called "Command Substitution".
Bash allows $()
for command substitution, but this is not available in all shells. I don't know if this is available at KSH; if so, it may not be available in all versions.
If the syntax $()
is available in your version of ksh, you must use it; easier to read (backticks are too easy to mix with single quotes); back-ticks are also hard to nest.
This only addresses one of the problems with your command: it ls
returns directories as well as files, so if the last changed in the specified directory is a subdirectory, that's what you'll see.
If you only want to see files, I suggest using some version of the following (I am using Bash which supports variables by default, you may have to play around with the syntax $1
)
lastfile ()
{
find ${1:-.} -maxdepth 1 -type f -printf "%T+ %p\n" | sort -n | tail -1 | sed 's/[^[:space:]]\+ //'
}
Searches a directory and extracts files from that directory. It formats all files as follows:
2012-08-29+16:21:40.0000000000 ./.sqlite_history
2013-01-14+08:52:14.0000000000 ./.davmail.properties
2012-04-04+16:16:40.0000000000 ./.DS_Store
2010-04-21+15:49:00.0000000000 ./.joe_state
2008-09-05+17:15:28.0000000000 ./.hplip.conf
2012-01-31+13:12:28.0000000000 ./.oneclick
sorts the list, takes the last line, and discards everything before the first space.
source to share
You need both quotes so that you keep the name even if it contains spaces, and also if you need more than 1 file, and "$ (..)" to run commands in the background
I believe you also need the "-1" option for ls, otherwise you may have multiple names per line (you only store one line, but there may be multiple files)
PRODUCT="$(ls -1t /some/dir/file* | head -1 | xargs -n1 basename)"
Don't put space around the "=" variable assignments (as I've seen on other solutions here), as it's not very compatible either.
source to share