blackstone8
blackstone8

Reputation: 65

Saving an *expression* to a shell variable, not the *result* of an expression

Problem :

I want to get the latest csv file in the downloads folder by typing $LATEST. When I dereference $LATEST I want to see the last csv file put in there.

What I have tried :

  1. 'ls -t $DL/*.csv | head -1' (this works)
  2. export $LATEST='ls -t $DL/*.csv | head -1'

The problem with 2. is it always returns the latest file at the time export is run. (e.g. old.csv) When I add a new file (e.g. new.csv) I want $LATEST to show new.csv not old.csv.

Upvotes: 0

Views: 76

Answers (3)

chepner
chepner

Reputation: 532238

If you can use zsh, it's much easier:

$ latest () { print "$DL"/*.csv(om[1]) }

The glob qualifier om sorts the expansion of "$DL"/*.csv by date; the [1] selects on the first element of the sorted expansion.

This avoids any concern about filenames containing newlines, which is the reason why parsing the output of ls should be avoided in theory.

Upvotes: 2

bishop
bishop

Reputation: 39444

Variables don't track changes in system state. They have values. Those values persist until you change them. If you want variable-like access to the current state, use a function. Example:

latest() {
    ls -t $DL/*.csv | head -1
}

echo "The latest file is $(latest)"
if [ "new.csv" = "$(latest)" ]; then
    echo "Hooray, new is latest!"
fi

A side benefit is that functions can take arguments. For example, if you wanted to make your latest function generic, but with reasonable defaults, you could do:

latest() {
    ls -t ${1:-$DL}/*.csv | head -${2:-1}
}
latest # show the 1 latest file from $DL directory
latest /tmp # show the 1 latest file from /tmp
latest /tmp 5 # show the five latest files from /tmp

In this case

Upvotes: 2

laughedelic
laughedelic

Reputation: 6460

The environment variable won't get updated automatically, it just stores the value. But you can define a function that will evaluate the expression from 1. every time your call it:

function latest {
  ls -t $DL/*.csv | head -1
}

Now if you put it in your ~/.bashrc and reload, you can call latest to evaluate the expression and get the result.

Upvotes: 2

Related Questions