You can create a file using the
> redirection operator wither with a command (
command > file) or by itself:
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:
So, in a script, if you want to prompt the user for a file name and create it, you could do:
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"
read -p "Enter a different file name: " fileName
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):
$ echo "$randomFileName"