19

I am trying to run a command

mv /var/www/my_folder/reports.html /tmp/

it is running properly. But I want to put a condition like if that file exists then only run the command. Is there anything like that?

I can put a shell file instead. for shell a tried below thing

if [ -e /var/www/my_folder/reports.html ]
  then
  mv /var/www/my_folder/reports.html /tmp/
fi

But I need a command. Can some one help me with this?

Gabriel
  • 3
  • 3
Maharjun M
  • 853
  • 4
  • 11
  • 24

4 Answers4

23

Moving the file /var/www/my_folder/reports.html only if it exists and regular file:

[ -f "/var/www/my_folder/reports.html" ] && mv "/var/www/my_folder/reports.html" /tmp/
  • -f - returns true value if file exists and regular file
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 1
    What if the file doesn't? Does it throw an error and change the status code from 0 to 1 or returns false (which isn't mean the command was broken with an error)? – uzay95 May 13 '20 at 15:20
  • 1
    @uzay95 No, it just returns false. – mbomb007 May 12 '22 at 13:21
7

if exist file and then move or echo messages through standard error output

test -e /var/www/my_folder/reports.html && mv /var/www/my_folder/reports.html /tmp/ || echo "not existing the file" >&2
Daein Park
  • 4,393
  • 2
  • 12
  • 21
1

Maybe your use case is "Create if not exist, then copy always". then: touch myfile && cp myfile mydest/

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

You can do it simply in a shell script

#!/bin/bash

# Check for the file
ls /var/www/my_folder/ | grep reports.html > /dev/null

# check output of the previous command
if [ $? -eq 0 ]
then
    # echo -e "Found file"
    mv /var/www/my_folder/reports.html /tmp/
else
    # echo -e "File is not in there"
fi

Hope it helps

Vipin Yadav
  • 1,616
  • 1
  • 14
  • 23