Xtigyro
Xtigyro

Reputation: 411

Set a Variable Using Subshelling Only at a Certain Step

How to set a variable that consists of the result of other commands only at a certain step in the script?

PENULTIMATE_F="$(ls -t "${LOGS_DIR_DS}" | head -n 2 | tail -1)"
LAST_F="$(ls -t "${LOGS_DIR_DS}" | head -n 1)"

Currently the values are not the latest two files created in the directory when that code of the script was executed but the ones that were present at the start of the script.

Explanation and answer: I needed this for a monitoring script which I wrote. The issue was completely different and I was not going crazy - which is a good thing. If you initialize a variable at a later point in a function - it does load the current and expected content. My issue was actually with creating an empty file - and because it was with no content - a short "if" function whether it existed or not and if not - to create it... well, actually the last file was created not until that later moment exactly because beforehand no real content was 'echo'-ed into that file.

Thank you for your clues which actually gave me confidence that the error was elsewhere!

Upvotes: 0

Views: 27

Answers (1)

John Kugelman
John Kugelman

Reputation: 361710

Easy answer: initialize the variables later.

Or: Use functions instead of variables. Then you can call the functions any time you like for updated results.

penultimateFile() { ls -t "${LOGS_DIR_DS}" | head -n 2 | tail -1; }
lastFile()        { ls -t "${LOGS_DIR_DS}" | head -n 1; }
PENULTIMATE_F=$(penultimateFile)
LAST_F=$(lastFile)

Upvotes: 1

Related Questions