Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am trying to make a bash script to clear my RAM caches.

Here's what I have so far:

#! /bin/bash

free -m
sync
sudo -s
echo 3 > /proc/sys/vm/drop_caches

But it doesn't fully work. The first three commands work perfectly, at the fourth command it exits.

Please explain.

share|improve this question
add comment

1 Answer 1

sudo -s creates a login shell session. Then after you exit that it, you return to being a regular user. Then it executes the 4th line, but you aren't root at that point so it fails.

You can't simply stick a sudo in front of the echo statement since that's a built-in command.

So try this instead:

#!/bin/bash

free -m
sync
sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"

From man sudo:

-s [command]
     The -s (shell) option runs the shell specified by the SHELL 
environment variable if it is set or the shell as specified in passwd(5).
If a command is specified, it is passed to the shell for execution. 
Otherwise, an interactive shell is executed.
share|improve this answer
    
If X is running, I believe it needs to be stopped sudo /etc/init.d/xdm stop. –  Zuul Jun 29 '12 at 23:27
    
@Zuul, the script will certainly run inside an X session (I just did). Whether it clears the cache or not I didn't check. –  Bryce Jun 30 '12 at 0:03
    
@Zuul, also that command stops X only if using xdm, which is not the default display manager. The right command would be sudo service lightdm stop. –  Bryce Jun 30 '12 at 0:05
    
yes, something along those lines, was just an example because I remembered not getting the proper result with X running. But thanks for adding the comment. Will try to add an answer to this question concerning all the facts from my experience. –  Zuul Jun 30 '12 at 0:30
    
Thanks man, it's worked. but faceing another problem, i add an extra command after 3rd line. it was free -m to see the difference. But it stops in line three. –  ScareCrow Jun 30 '12 at 12:30
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.