Maharjun M
Maharjun M

Reputation: 923

move or copy a file if that file exists?

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?

Upvotes: 22

Views: 37936

Answers (4)

Vipin Yadav
Vipin Yadav

Reputation: 1658

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

Upvotes: 0

Daein Park
Daein Park

Reputation: 4693

If the file exists 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

Upvotes: 8

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93193

Maybe your use case is "Create if not exist, then copy always". Then:

touch myfile && cp myfile mydest/

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 25

Related Questions