1

I have Nginx running in Ubuntu. I'm trying to write a script that deletes an item from the Nginx cache.

Script: clear_single_cache_object.sh

#!/bin/bash
echo "Deleting: " $1
grep -lr $1 /path/to/cache/* | xargs rm
echo "Done"

This script is in my home directory and I execute the script in the termial as follows:

sh clear_single_cache_object.sh '/images/test.jpg'

The output is this:

Deleting: /images/test.jpg
: No such file or directory
Done

In other words, the script is not working and the item has not been removed from the cache. I have also tried to run the script as root.

If I type the following command in the terminal, then it works fine and the item is removed from the cache.

grep -lr '/images/test.jpg' /path/to/cache/* | xargs rm

Why does it not work when I run the script? I suspect that it has something to do with the " | xargs rm" part in the script.

7
  • That was a typo. I have made the correction.
    – thd
    Feb 19, 2015 at 14:47
  • Since the error message appears to be overwriting the filename, I would conclude that the nginx cache uses \r\n line endings. Try grep -lr $1 /path/to/cache/* | od -c to test my guess. Feb 19, 2015 at 14:55
  • Have you tried "%1" instead of %1?
    – desgua
    Feb 19, 2015 at 14:59
  • @glenn jackman - with "od -c" I get the message "d: invalid option --".
    – thd
    Feb 19, 2015 at 15:03
  • @desgua - yes I have tried that and it didn't work.
    – thd
    Feb 19, 2015 at 15:05

1 Answer 1

1

First, glen jackman was close: your script is using CR-LF (\r\n) line endings. For example, I recreated your script with CRLF line endings manually:

$ cat foo.sh     
#!/bin/bash
echo "Deleting: " $1
grep -lr $1 foo.txt | xargs echo
echo "Done"
$ file foo.sh 
foo.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
$ sh foo.sh bar
Deleting:  bar
: No such file or directory
Done

Change your line endings to the normal form, by installing dos2unix and using it to convert:

sudo apt-get install dos2unix
dos2unix clear_single_cache_object.sh

Second, since you're giving a shebang, why are you calling your script with sh? Make it executable and run it drectly:

chmod +x clear_single_cache_object.sh
./clear_single_cache_object.sh /images/test.jpg

If you'd done that, you could have caught the problem earlier:

$ ./foo.sh 
bash: ./foo.sh: bad interpreter: /bin/bash^M: no such file or directory

Third, fix your editor. If you're creating the script on Windows and then copying to your server, use a decent editor like Notepad++ which supports Unix line endings (LF).

1
  • It's working now. Thanks for your advice about sh and shebang. I'm new to the world of Linux.
    – thd
    Feb 23, 2015 at 20:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .