-1

In CentOS with Bash I download a file with a very trivial file name, install.sh.

Although extremely unlikely in my scenario, this could still, in theory, overwrite some existing file with the same name.

How would you solve this problem?


If I understood correctly, one way to deal with this is:

cd DOWNLOADS &&
source <( wget --quiet -O - 'URL/install.sh' )

But as a non professional sysadmin I seek a more "basic" or "simple" way because I am having hard time working with the <(...) syntax, let along with downloading to stdout with various options.

I was thinking about:

  • Download a file with a randomly created long file name
  • Do action with the file (such as cp and mv to change name)
  • delete the downloaded file

Perhaps something like this pseudocode:

random_name=(wget -O kjghfkjdhsgkj.sh URL) # How to create random name by the computer?
destination=(cp "${random_name}" DESTINATION)
mv "${destination}" NEW_DESTINATION
rm "${random_name}"
6
  • Why would you want to move the randomly named file to a known name? Wouldn't that defeat the purpose of having the randomly generated name in the first place? Just download the script to a random filename, like I mentioned to you before, and then run that script.
    – Kusalananda
    Commented Mar 27, 2021 at 8:28
  • I thought that while the file is randomly-named, I could run some test to check if there is already a file with the known name and if not, store it as with the known name. But I know figure that I could make the test before downloading and only if there is no file with the original known name in the download destination --- then download.
    – timesharer
    Commented Mar 27, 2021 at 9:20
  • I have edited the title to not be "XY problem" reflective.
    – timesharer
    Commented Mar 27, 2021 at 9:22
  • "Make a test before downloading" gives you TOCTOU. This is why we should use mktemp, it is designed to solve such problems. Commented Mar 27, 2021 at 9:46
  • @KamilMaciorowski thanks, I never came across this concept before.
    – timesharer
    Commented Mar 27, 2021 at 10:01

1 Answer 1

2

mktemp is exactly here to let us create a file with a "semi-random" templated filename. See man mktemp; and for cleaning part, see trap.

2
  • Randomly-but-not-by-a-computer (in my case, by a human) is "semi-random"?
    – timesharer
    Commented Mar 27, 2021 at 8:24
  • @timesharer For bigger projects consider mktemp -d. It creates a temporary directory, initially empty, so you can use fixed and meaningful names inside. Its your job to make them not to collide with one another, but they won't collide with anything external. Cleaning is trivial: you remove the entire directory. Commented Mar 27, 2021 at 8:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .