When creating a file in bash, how can I use 2> / dev / null if it cannot be created?

I am creating a script that will calculate some other directory information. I must provide the user with the ability to create the file. Many different file checks are performed, but in particular this upsets:

If the file name is marked and does not exist, the script should try to create it. If creation failed, the user must be notified that he cannot be created.

So, I have a variable (file) that is the name that the user provided to the file that he wants to create. Then I use:

echo -n "Creating the file: '$file'" touch "$file" if [ -e "$file" ]; then echo "..........File created" else echo"...........Creation failed" fi 

Is> 2 / dev / null running after the touch line? What will be the correct syntax for suppressing the error message and only the display will be displayed File creation: (file) ......... Creation failed?

Many thanks

+4
source share
2 answers

You need to use 2> , not >2 to redirect the standard error.

 touch "$file" 2> /dev/null 

But even with this change, your script has an error:

Suppose touch fails because the file exists, but you do not have permission to touch it. Then you check if the file exists using the -e check, which returns true , and you print File created , which is incorrect.

To fix this, you need to check the return value of the touch command as:

 if touch "$file" 2> /dev/null ; then echo "..........File created" else echo "..........File failed" 
+3
source

Do you really want:

 touch "$file" 2> /dev/null 

(note 2> not >2 )

0
source

All Articles