-2

How can I create a random file using bash on Linux and how is it possible to delete a created file? I am not sure.

Idea: The user should enter an arbitrary file name and save it. They can also delete this saved file.

Thanks in advance

Code to delete a file:


    if [ "$REPLY" = "d" ];                                                                             

        then

        read -r -p 'Delete file: Please enter the name of the file to delete: ' -a delete_file 

        echo -e "\nFile was deleted: ${delete_file[*]}\n"                                  

        break

    fi

4
  • Do you want a random file name or do you want the user to choose a file name?
    – terdon
    Jun 12 at 10:44
  • A random file name. Users should enter a name and confirm it.
    – Coder_74ZB
    Jun 12 at 10:46
  • 3
    Those are mutually exclusive: either the user enters a name, or you want to generate a random name. Which one do you want?
    – terdon
    Jun 12 at 10:47
  • The first one. The user enters a name.
    – Coder_74ZB
    Jun 12 at 10:48

1 Answer 1

2

You can create a file using the > redirection operator wither with a command (command > file) or by itself:

> file

Note that this will overwrite the contents of file if a file with that name already exists. If no such file exists, an empty one will be created.

Alternatively, you can use the touch command which will also create a file if a file with the name you give it doesn't already exist, but will not overwrite the contents of an existing file. If a file with that name exists, the touch command will update its modification timestamp:

touch file

So, in a script, if you want to prompt the user for a file name and create it, you could do:

#!/bin/bash

read -p "Enter a file name: " fileName
echo "You entered: '$fileName'"

while [ -e "$fileName" ]; do
   read -p "A file named '$fileName' already exists, delete? [y/n]: "
   if [ "$REPLY" = "y" ]; then
     rm -- "$fileName"
   else
      read -p "Enter a different file name: " fileName
   fi
done

touch -- "$fileName"

To make a file with a random name, the best tool is mktemp which will make sure that the name is unique in the target directory (see man mktemp for details):

$ randomFileName=$(mktemp)
$ echo "$randomFileName"
/tmp/tmp.QLLdNLFBFd
1
  • I will try it. Thank you.
    – Coder_74ZB
    Jun 12 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.