Linux delete file if exist

Linux filename check if exist and delete

I have some problem in Shell scripting. So I have to write a script that find every file in a directory with this string: «gom». So i found all of them. After I need to cut it off, and compare that the remaining filename is exist. If exist i need to remove the file that contains the string. Example: there are 5 files: algomb, gomba, alb, algomba, alba. I need to find the filenames with «gom». algomb, gomba, algomba. After it i need to cut the «gom». And a remaining filenames is exist I need to remove the file with «gom» string. So after the cutting «gom» there will be 5 files: alb, ba, alb, alba, alba So there are two files that is extist: alb, alba. I need to remove the following files: algomb, albomba. After it the will be 3 files: gomba, alb, alba. Sorry for my bad english. I can find, I can remove, but I cant compare the filenames. Here’s my code:

#!/bin/bash sz="gom" talal=`find . -type f -name "*$sz*" -exec basename <> \;` ossz=`find . -type f -exec basename <> \;` c=`echo $$` for c in ossz; do if [ ! -d ]; then echo "This is a directory" else if [ -f ]; then find .-type f -name "*$sz*" -exec basename <> \; else echo $$ fi fi done 

So this is works. This echo $$ is give back the filename without «gom». But I cant compare these values with find . -type f -exec basename <> \; results. Sorry for my bad english. Can sombody help me? Best regards, Richard

2 Answers 2

I would do it this way, without find .

shopt -s globstar for gom_file in **/*gom*; do # Skip non-regular files [[ -f $gom_file ]] || continue # Delete the file if the gom-free file exists [[ -f $ ]] && rm "$gom_file" done 

Using find is slightly less efficient, since you need to fork a new shell for each file:

find . -type f -name "*gom*" -exec bash -c 'echo rm -f "$"' <> \; 

Run this to test that it outputs the rm commands you want to execute, then run it again with echo removed.

Источник

How to delete a file in bash

Any file can be deleted temporarily and permanently in bash. When a file is removed temporarily by using a graphical user interface, then it is stored in the Trash folder, and it can be restored if required. The file which is removed permanently cannot be restored later normally. `rm` command is used to remove the file permanently from the computer. If any file is removed accidentally by this command, then it can be restored from the backup. How any file can be removed from the terminal and the graphical user interface are shown in this article.

Читайте также:  Kali linux spoof dns

Delete the file using `rm` command:

`rm` command can be used with option and without the option for the different types of delete. The syntax of the `rm` command is given below.

Syntax:

‘-i’ option can be used with `rm` command to provide a prompt before deleting any file to prevent accidental deletion. ‘-f’ option can be used with `rm` command to remove any file forcefully. The different uses of the `rm` command are shown below.

Example-1: Delete the file using `rm` command without the option

You can apply the ‘rm’ command to remove an existing file. In the following script, an empty file is created by using the ‘touch’ command to test ‘rm‘ command. Next, ‘rm’ command is used to remove the file, test.txt.

# Set the filename
filename = ‘test.txt’
# Create an empty file
touch $filename
# Check the file is exists or not
if [ -f $filename ] ; then
rm test.txt
echo » $filename is removed»
fi

Example-2: Delete the file using `rm` command with -i option

The following script will ask for permission from the user before removing the file for ‘-i’ option. Here, the filename will be taken from the user as input. If the file exists and the user press ‘n’ then the file will not remove otherwise the file will remove.

# Take the filename
read -p ‘Enter the filename to delete: ‘ filename

# Check the file is exists or not
if [ -f $filename ] ; then
# Remove the file with permission
rm -i » $filename »
# Check the file is removed or not
if [ -f $filename ] ; then
echo » $filename is not removed»
else
echo » $filename is removed»
fi
else
echo «File does not exist»
fi

Example-3: Delete the file using `rm` command with -v option

The following script will take the filename by a command-line argument. If the file exists then, it will print a remove message with the filename for ‘-v’ option.

# Check the file is exists or not
if [ [ $1 ! = «» && -f $1 ] ] ; then
# Print remove message
rm -v $1
else
echo «Filename is not provided or filename does not exist»
fi

Example-4: Delete multiple files using `rm` command

More than one file can be deleted by using ‘rm’ command and separating the filenames with space. In the following script, multiple filenames will be taken from the command line arguments. If any file does not exist, then it will show a message otherwise filenames will be combined by the space and stored into the variable named ‘files’. Next, the rm command will be executed with the ‘files’ variable to remove multiple files.

# Check the multiple filenames are given or not
if [ $# > 2 ] ; then
# Reading argument values using loop
for argval in «$@»
do
if [ -f $argval ] ; then
files+= $argval $space
else
echo » $argval does not exist»
fi
done

# Remove files
rm $files
echo «files are removed.»
else
echo «Filenames are not provided, or filename does not exist»
fi

Читайте также:  При обновлении линукс минт ошибка

Conclusion:

The above examples show the different types of ways to delete the file using a bash script to help bash users to do this type of task easily.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Thread: shell script to delete a file if it exists

tapas_mishra is offlineQuad Shot of Ubuntu

shell script to delete a file if it exists

I am writing a shell script to delete a file if it exists.
The script I wrote is

#!/bin/bash if [ -f q1.txt] ; then rm q1.txt fi

geirha is offlineUbuntu addict and loving it

Re: shell script to delete a file if it exists

tapas_mishra is offlineQuad Shot of Ubuntu

Re: shell script to delete a file if it exists

Hmm no I am trying to write an init script which deletes the file.
If it exists.I am not clear as how do I detect the process running so I asked in simple way.
I mean grabbing the pid and killing the process upon reboot.

geirha is offlineUbuntu addict and loving it

Re: shell script to delete a file if it exists

When you start the process, you write the pid to a file. Then you just read the pid from that same file when you want to kill it. And of course, remove the file when you’ve killed it.

tapas_mishra is offlineQuad Shot of Ubuntu

Re: shell script to delete a file if it exists

ps -el | grep pulseaudio 1 S 1000 3863 1 0 80 0 - 23663 poll ? 00:00:00 pulseaudio

geirha is offlineUbuntu addict and loving it

Re: shell script to delete a file if it exists

Also, pulseaudio can be killed by running

tapas_mishra is offlineQuad Shot of Ubuntu

Re: shell script to delete a file if it exists

My question is not ps.
If I change my question
ls -l will give some output is there a way to store the different columns coming out of the result of the command
VAR=`ls -l`
so that I can use them as separate arguments.

soltanis is offlineDark Roasted Ubuntu

Re: shell script to delete a file if it exists

It is still not clear why you insist on not using the -f switch for rm, but you have several options: cut and awk.

ghostdog74 is offlineI Ubuntu, Therefore, I Am

Re: shell script to delete a file if it exists

QuoteOriginally Posted by geirha View Post

although it raises some points to take note of, ps is still universally available in most *nix, and it should be used when the situation is necessary.

ghostdog74 is offlineI Ubuntu, Therefore, I Am

Re: shell script to delete a file if it exists

QuoteOriginally Posted by tapas_mishra View Post

I am writing a shell script to delete a file if it exists.
The script I wrote is

#!/bin/bash if [ -f q1.txt] ; then rm q1.txt fi
#!bin/bash file="q1.txt" [[ -f "$file" ]] && rm -f "$file"
  • Site Areas
  • Settings
  • Private Messages
  • Subscriptions
  • Who’s Online
  • Search Forums
  • Forums Home
  • Forums
  • The Ubuntu Forum Community
    1. Ubuntu Official Flavours Support
      1. New to Ubuntu
      2. General Help
      3. Installation & Upgrades
      4. Hardware
      5. Desktop Environments
      6. Networking & Wireless
      7. Multimedia Software
    2. Ubuntu Specialised Support
      1. Ubuntu Development Version
      2. Security
      3. Virtualisation
      4. Ubuntu Servers, Cloud and Juju
        1. Server Platforms
        2. Ubuntu Cloud and Juju
      5. Gaming & Leisure
        1. Emulators
      6. Wine
      7. Development & Programming
        1. Packaging and Compiling Programs
        2. Development CD/DVD Image Testing
        3. Ubuntu Application Development
        4. Ubuntu Dev Link Forum
        5. Programming Talk
        6. Repositories & Backports
          1. Ubuntu Backports
            1. Bug Reports / Support
      8. System76 Support
      9. Apple Hardware Users
    3. Ubuntu Community Discussions
      1. Ubuntu, Linux and OS Chat
        1. Recurring Discussions
        2. Full Circle Magazine
      2. The Cafe
        1. Cafe Games
      3. Market
      4. Mobile Technology Discussions (CLOSED)
      5. Announcements & News
      6. Weekly Newsletter
      7. Membership Applications
      8. The Fridge Discussions
      9. Forum Council Agenda
      10. Forum Feedback & Help
        1. Request a LoCo forum
      11. Resolution Centre
    4. Other Discussion and Support
      1. Other OS Support and Projects
        1. Other Operating Systems
          1. Ubuntu/Debian BASED
          2. Debian
          3. MINT
          4. Arch and derivatives
          5. Fedora/RedHat and derivatives
          6. Mandriva/Mageia
          7. Slackware and derivatives
          8. openSUSE and SUSE Linux Enterprise
          9. Mac OSX
          10. PCLinuxOS
          11. Gentoo and derivatives
          12. Windows
          13. BSD
          14. Any Other OS
      2. Assistive Technology & Accessibility
      3. Art & Design
      4. Education & Science
      5. Documentation and Community Wiki Discussions
      6. Tutorials
        1. Outdated Tutorials & Tips
      7. Ubuntu Women
      8. Ubuntu LoCo Team Forums
        1. Americas LoCo Teams
          1. Argentina Team
            1. Software
            2. Hardware
            3. Comunidad
          2. Arizona Team — US
          3. Arkansas Team — US
          4. Brazil Team
          5. California Team — US
          6. Canada Team
          7. Centroamerica Team
          8. Chile Team
            1. Comunidad
            2. Hardware
            3. Software
            4. Instalaci�n y Actualizaci�n
          9. Colombia Team — Colombia
          10. Georgia Team — US
          11. Illinois Team
          12. Indiana — US
          13. Kentucky Team — US
          14. Maine Team — US
          15. Minnesota Team — US
          16. Mississippi Team — US
          17. Nebraska Team — US
          18. New Mexico Team — US
          19. New York — US
          20. North Carolina Team — US
          21. Ohio Team — US
          22. Oklahoma Team — US
          23. Oregon Team — US
          24. Pennsylvania Team — US
          25. Peru Team
          26. Texas Team — US
          27. Uruguay Team
          28. Utah Team — US
          29. Virginia Team — US
          30. West Virginia Team — US
        2. Asia and Oceania LoCo Teams
          1. Australia Team
          2. Bangladesh Team
          3. Hong Kong Team
          4. Myanmar Team
          5. Philippine Team
          6. Singapore Team
        3. Europe, Middle East, and African (EMEA) LoCo Teams
          1. Albania Team
          2. Catalan Team
          3. Portugal Team
          4. Egypt Team
          5. Georgia Team
          6. Ireland Team — Ireland
          7. Kenyan Team — Kenya
          8. Kurdish Team — Kurdistan
          9. Lebanon Team
          10. Morocco Team
          11. Saudi Arabia Team
          12. Sudan Team
          13. Tunisia Team
        4. Other Forums & Teams
        5. LoCo Archive
          1. Afghanistan Team
          2. Alabama Team — US
          3. Alaska Team — US
          4. Algerian Team
          5. Andhra Pradesh Team — India
          6. Austria Team
          7. Bangalore Team
          8. Bolivia Team
          9. Cameroon Team
          10. Colorado Team — US
          11. Connecticut Team
          12. Costa Rica Team
          13. Delhi Team
          14. Ecuador Team
          15. El Salvador Team
          16. Florida Team — US
          17. Galician LoCo Team
          18. Greek team
          19. Hawaii Team — US
          20. Honduras Team
          21. Idaho Team — US
          22. Iowa Team — US
          23. Jordan Team
          24. Kansas Team — US
          25. Libya Team
          26. Louisiana Team — US
          27. Maryland Team — US
          28. Massachusetts Team
          29. Michigan Team — US
          30. Missouri Team — US
          31. Montana Team — US
          32. Namibia Team
          33. Nevada Team — US
          34. New Hampshire Team — US
          35. New Jersey Team — US
          36. Northeastern Team — US
          37. Panama Team
          38. Paraguay Team
          39. Qatar Team
          40. Quebec Team
          41. Rhode Island Team — US
          42. Senegal Team
          43. South Carolina Team — US
          44. South Dakota Team — US
          45. Switzerland Team
          46. Tamil Team — India
          47. Tennessee Team — US
          48. Trinidad & Tobago Team
          49. Uganda Team
          50. United Kingdom Team
          51. US LoCo Teams
          52. Venezuela Team
          53. Wales Team
          54. Washington DC Team — US
          55. Washington State Team — US
          56. Wisconsin Team
          57. Yemen Team
          58. Za Team — South Africa
          59. Zimbabwe Team
Читайте также:  Сменить имя пользователя линукс

Bookmarks

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Источник

Оцените статью
Adblock
detector