- How to Run or Repeat a Linux Command Every X Seconds Forever
- 1. Use watch Command
- Monitor Memory Usage
- Monitor Logged-In Users, Uptime and Load Average
- Monitor Progress of Copy Command
- 2. Use sleep Command
- for loop Example
- while loop Example
- Conclusion
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Repeat last command with «sudo»
- 5 Answers 5
- Different Ways To Repeat Your Last Command In Linux
- Repeat last command in Linux
- Method 1 — Using exclamation marks
- Method 2 — Repeat N-th command
- Method 3 — Using reverse-search
- Method 4 — Use hyphen symbol with command prefix numbers
- Method 5 — Using CTRL+p and CTRL+o
- Method 6 — Using fc command
- Method 7 — Using ALT+period key
How to Run or Repeat a Linux Command Every X Seconds Forever
A system administrator often needs to run a command repeatedly in a certain periods of time. Often such tasks can be easily completed with simple cron commands. In most of the cases this should work, but the shortest period which you can run cron command is every 1 minute. Believe it or not, in many cases this is too slow.
Run Linux Command Every Second
In this tutorial, you will learn a simple scripting techniques to monitor or keep a eye on a particular command in continuously running state similar to top command (continuously monitor the process and memory utilization) for every 3 seconds by default.
We will not stop to discuss the reasons, why you would need to run commands this often. I believe everyone has different reasons for that in their daily jobs or even at home PCs and laptops.
1. Use watch Command
Watch is a Linux command that allows you to execute a command or program periodically and also shows you output on the screen. This means that you will be able to see the program output in time. By default watch re-runs the command/program every 2 seconds. The interval can be easily changed to meet your requirements.
Monitor Memory Usage
“Watch” is extremely easy to use, to test it, you can fire up a Linux terminal right away and type the following command:
The above command will check your system free memory and update the results of the free command every two seconds.
Monitor Memory Usage in Linux
As seen per the above output, you have a header, displaying information about (from left to right) update interval, command that is being executed and current time. If you wish to hide this header, you can use the -t option.
The next logical question is – how to change the execution interval. For that purpose, you can use the -n option, that specifies the interval with which the command will be executed. This interval is specified in seconds. So let’s say you want to run your script.sh file every 10 seconds, you can do it like this:
Note that if you run the command like shown above, you will need to cd to the directory (learn Learn 15 cd Command Examples) where the script is located or otherwise specify the full path to that script.
Other useful options of watch command are:
- -b – creates a beep sound if the exit of the command is non-zero.
- -c – Interprets ANSI color sequences.
- -d – highlights the changes in the command output.
Monitor Logged-In Users, Uptime and Load Average
Let’s say you want to monitor logged-in users, server uptime and load average output in continuously phase every few seconds, then use following command as shown:
Watch Linux Load Average
To exit the command, press CTRL+C .
Here, the ‘uptime’ command will run and display the updated results every 2 seconds by default.
Monitor Progress of Copy Command
In Linux, while copying files from one location to other using cp command, the progress of data is not shown, to see the progress of data being copied, you can use the watch command along with du -s command to check the disk usage in real time.
Monitor Progress of Copy Command
If you think that the above process is too complicated to achieve, then I suggest you to go for Advance copy command, which shows progress of data while copying.
2. Use sleep Command
Sleep is often used to debug shell scripts, but it has many other useful purposes as well. For example, when combined with for or while loops, you can get pretty awesome results.
If you are new to bash scripting, you can check our guide about bash loops here.
In case this is the first time you hear about the «sleep» command, it is used to delay something for a specified amount of time. In scripts, you can use it to tell your script to run command 1, wait for 10 seconds and then run command 2.
With the above loops, you can tell bash to run a command, sleep for N amount of seconds and then run the command again.
Below you can see examples of both loops:
for loop Example
The above one liner, will run the echo command and display the current date, total of 10 times, with 5 seconds sleep between executions.
Here is a sample output:
You can change the echo and date commands with your own commands or script and change the sleep interval per your needs.
while loop Example
Here is sample output:
The above command will run until it is either killed or interrupted by the user. It can come in handy if you need to run a command running in the background and you don’t want to count on cron.
Important: When using the above methods, it is highly recommend that you set interval long enough to give enough time of your command to finish running, before the next execution.
Conclusion
The samples in this tutorial are useful, but are not meant to completely replace the cron utility. It is up to you to find which one works better for you, but if we have to separate the usage of both techniques, I would say this:
- Use cron when you need to run commands periodically even after system reboots.
- Use the methods explained in this tutorial for programs/scripts that are meant to run within the current user session.
As always if you have any questions or comments, do not hesitate to submit them in the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Repeat last command with «sudo»
I often forget to run commands with sudo . I’m looking for a way to make a bash function (or alias) for repeating the last command with sudo . Something like:
5 Answers 5
if you want the S simply put:
the !! mean the last command
Use alias redo=’sudo $(history -p !!)’ . This is the only thing that I have found that works with aliases. The other answers do not work in aliases for some reason, having tried them myself, even though they do work when directly running them.
!! can be used to reference the last command. So:
Adding and expanding upon aaron franke’s response (which is correct but lacking a why) such that simply typing redo works after configuring the alias alias redo=’sudo $(history -p !!) ;
This is the only thing I found that works with aliases
There are a few things going on that warrant explanation.
doesn’t work as it doesn’t execute the sudo portion, though it does resolve the !! .
To get the sudo !! to resolve correctly, a shell resolution directive has to execute and concatenate along with sudo . So we do;
By specifying the right side of the alias to $(history -p !!) , what this does is say to the shell;
- redo is an alias, assess the right side of the =
- sudo remains as is and it concatenated to.
- $() is a shell directive, to execute the contents within the current execution process (as oppose to a sub-shell $<> , which spawns a different process to execute within)
- Resolve history -p !!
- The !! gets expanded to history -p as a result of step 4.
- The -p part says to history to only print the results, not execute
- The sudo , executes the remaining (now printed out on the same command line), with elevated privileges, assuming password was entered correctly
This ultimately means that the command history -p !! effectively writes out the resolution rather than executing after the sudo .
NOTE: The ‘ is significant. If you use » , the !! gets interpolated twice and to achieve our purpose we need to very carefully control the resolution steps; single/double quotes in bash
PS
If you’re using zsh + oh-my-zsh , there is a sudo alias setup for _ such that you can do;
Which will rerun the last command as sudo . However, if you’re configuring the alias in
/.zshrc , the alias redo=’sudo $(history -p !!) will not work as is from the zsh config as the resolution steps are different.
That said, you can put the alias into
/.bashrc instead of
/.zshrc and have the same result when executing the alias redo from zsh (assuming you’re sub-shelling zsh from bash, though this is admittedly a bit of a kludge — though a functional one).
Источник
Different Ways To Repeat Your Last Command In Linux
Today, I will be teaching you how to repeat your last command in Linux. You don’t have to re-type the previously executed commands in your Shell. Of course, we use the UP arrow key to select the last executed commands and hit ENTER to execute them. However, there are also other a few ways to do this. There could be many ways to repeat the last commands in Unix-like systems, but these are the only ways I am aware of now. All these commands were tested in my Arch Linux and Ubuntu desktop with BASH shell.
A word of caution: When you try the following methods, the previously executed commands will run immediately. Just make sure your last command wasn’t any harmful like formatting a partition or deleting files, folders or any other important data.
Repeat last command in Linux
Let us run a few commands.
As I mentioned earlier, we can execute the last command by simply pressing the UP arrow and hit ENTER key. This is the most commonly used way by many users to execute the previous command. This method will work on all SHELL, regardless of the Linux distribution you use.
However, like I said already, there are a few other methods to do this.
Now, let me show you how to execute the last command with some practical examples.
Method 1 — Using exclamation marks
To execute any last executed command, just type double exclamation marks, and hit ENTER:
This will execute the last command. Sample output would be:
Add sudo in-front of !! to execute the last command as root user like below.
You can also use the following to execute the previous command as sudo user:
Sample output:
Cool, isn’t it? You don’t need to type the last command completely. It could be useful when you’ve already executed a very long command, and don’t want to re-type the same command again.
Method 2 — Repeat N-th command
You might have run so many commands, and want to repeat a specific command. What will you do? Simple! You can do this by typing a specific word of the previous command.
To repeat previous command that starts with a specific word/letter, for example un , just type:
The above command will execute last command that starts with the letters «un».
Sample output:
As you see in the above example, you don’t need to type the whole command (i.e uname -r ). Instead, just type a few letters of the command, and any previous command that contains words will run.
Also, If you know the full command name, just type it like below:
It will execute the last command.
What if you don’t want to repeat the last command, but just display it. Sometimes, you don’t want to run a command, but just retrieve it from the history. If so, find the prefix number of the command you want to run:
Sample output:
Let us say you want to retrieve the 1685th command, but don’t want to run it immediately, add :p next to the command like below.
This will display 1685th command from the history, but won’t execute it.
Method 3 — Using reverse-search
Another way to do this is by searching your command line history using CTRL+R . Press CTRL+R key to search through the command line history. I personally prefer this method. It searches history interactively which I think feels safer than executing commands blindly from the BASH history.
Have a look at the following example. In the following example, I searched for «ost» , which displayed the last command “sudo netctl restart ostechnixjio” in the history that contained the word «ost» . Then, I hit ENTER to execute the command immediately or right arrow key complete the command and hit ENTER key to execute it.
Just in case, you want to edit/modify the last command before executing it, just press the left arrow key, then edit the last command and hit ENTER to execute it. Some commands may start with same letters. In such cases, keep hitting the CTRL+R key to bring back the command you wanted to run.
Method 4 — Use hyphen symbol with command prefix numbers
Here is yet another way to run the previous command.
Sample output:
Similarly, !-2 will run the second last command, !-3 will run the third last command, and so on.
Method 5 — Using CTRL+p and CTRL+o
I don’t want to type any command manually. Is there any way to repeat a last command by simply pressing a particular key(s) in my Keyboard? Yes, of course!
Press CTRL+P to switch to the last command, and then press CTRL+O to execute it. This will do the wonder. No configuration needed! You can use CTRL+O as many times as you want to keep re-executing the last commands.
Method 6 — Using fc command
This is another way to repeat the last executed command. The fc command is used to list, edit and re-run the previously entered command.
To repeat the last command using fc, simply run:
Sample output:
Suggested read:
Method 7 — Using ALT+period key
As one of our reader said in the comment section, we can also use ALT+. keys (press ALT+period) to retrieve the last command without running it. However, there is one limitation. Hitting ALT+. will only retrieve the last argument in the command. For example, if your previous command is «uname -r» , it will only bring back the -r argument, but not the entire command.
And, that’s all. You know now how to repeat your last command without typing it in the Terminal. If you want to view the output of your last commands without actually having to retype them, these methods will help.
If you know any other methods, please let me know in the comment section below. I will check and update the guide accordingly.
You knew now how to repeat a previously executed command. How do you repeat a Linux command or program until it succeeds? Well, that’s easy! Refer the following guide for more details.
Источник