Linux повтор команды каждые

Repeat a command every x interval of time in terminal?

How can I repeat a command every interval of time , so that it will allow me to run commands for checking or monitoring directories ? There is no need for a script, i need just a simple command to be executed in terminal.

8 Answers 8

You can use watch command, watch is used to run any designated command at regular intervals.

change x to be the time in seconds you want.

For more help using the watch command and its options, run man watch or visit this Link.

For example : the following will list, every 60s, on the same Terminal, the contents of the Desktop directory so that you can know if any changes took place:

+1 but be careful when using expansions. For example, try the difference between watch -n 1 ‘echo $COLUMNS’ and watch -n 1 echo $COLUMNS when resizing your terminal — the former is expanded every second, but the latter is expanded only once before watch starts.

Problem I have with this solution is that you can’t run watch as a process and just leave it running in the background (for example with &disown)

Is there any way to use watch with «history enabled» type command? I love using watch , but sometimes I’d prefer to see a log of previous executions as well, instead of just the last one. And yes, I know I can use scripting ( while true ) to accomplish this, but using the watch utilitiy is so much cleaner!

this worked for simpler commands but with pipelined commands chaining this didn’t work for me.. following was the command I tried =>cat api.log | grep ‘calling’ | wc -l

You can also use this command in terminal, apart from nux’s answer:

while true; do ; sleep ; done 
while true; do ls; sleep 2; done 

This command will print the output of ls at an interval of 2 sec.

Use Ctrl + C to stop the process.

There are few drawbacks of watch :

  • It cannot use any aliased commands.
  • If the output of any command is quite long, scrolling does not work properly.
  • There is some trouble to set the maximum time interval beyond a certain value.
  • watch will interpret ANSI color sequences passing escape characters using -c or —color option. For example output of pygmentize will work but it will fail for ls —color=auto .

In the above circumstances this may appear as a better option.

I am not claiming this answer is to be used at first place. watch is good in most cases. That is why I mentioned «apart from nux’s answer» at the beginning. But there are few problems with watch for example One can not use any aliased commands with watch . Take for example ll which is aliased to ls -laF but can not be used with watch . Also in case if the output of any command is quite long you will be in trouble in scrolling using watch . In these few special cases this answer may appear a better option.

Читайте также:  Свой vds linux хостинг

Just wanted to pitch in to sourav c.’s and nux’s answers:

  1. While watch will work perfectly on Ubuntu, you might want to avoid that if you want your «Unix-fu» to be pure. On FreeBSD for example, watch is a command to «snoop on another tty line».
  2. while true; do command; sleep SECONDS; done also has a caveat: your command might be harder to kill using Ctrl + C . You might prefer:
while sleep SECONDS; do command; done 

Why exactly does it matter where you put sleep in the while loop? I couldn’t find any difference, Ctrl+C broke the loop instantly no matter what.

@dessert: depends on what you’re trying to break out from I guess. Normally, ctrl+c would just kill your command and sleep and only break if you kill true .

Sounds like the ideal task for the cron daemon which allows for running periodic commands. Run the crontab -e command to start editing your user’s cron configuration. Its format is documented in crontab(5). Basically you have five time-related, space-separated fields followed by a command:

The time and date fields are: field allowed values ----- -------------- minute 0-59 hour 0-23 day of month 1-31 month 1-12 (or names, see below) day of week 0-7 (0 or 7 is Sunday, or use names) 

For example, if you would like to run a Python script on every Tuesday, 11 AM:

0 11 * * 1 python ~/yourscript.py 

There are also some special names that replace the time, like @reboot . Very helpful if you need to create a temporary directory. From my crontab (listed with crontab -l ):

# Creates a temporary directory for ~/.distcc at boot @reboot ln -sfn "$(mktemp -d "/tmp/distcc.XXXXXXXX")" "$HOME/.distcc" 

The question asks how to run something periodically in the terminal. cron runs behind the scenes rather than in the terminal

you can use crontab. run the command crontab -e and open it with your preferred text editor, then add this line

This will run your command every 10 minutes

This will run your command every 4 hours

Another possible solution

$ ..some command. ; for i in $(seq X); do $cmd; sleep Y; done 

X number of times to repeat.

Y time to wait to repeat.

$ echo; for i in $(seq 5); do $cmd "This is echo number: $i"; sleep 1;done 

Why is this an improvement? You just added an extra, needless, step by saving the command as a variable. The only things this does is i) make it longer to type ii) forces you to use only simple commands, no pipes or redirects etc.

If you are monitoring the file system, then inotifywait is brilliant and certainly adds less load on your system.

In 1st terminal type this command :

Then in 2nd terminal, any command that affects the current directory,

Then in original terminal inotifywait will wake up and report the event

$ while true ; do inotifywait . ; done Setting up watches. Watches established. ./ OPEN newfile2 Setting up watches. Watches established. ./ OPEN newfile2 Setting up watches. Watches established. ./ DELETE newfile Setting up watches. Watches established. ./ CREATE,ISDIR newdir Setting up watches. Watches established. 

I didn’t tell him to write a script, I suggested that if they are looping inorder to watch for particular filesystem event, then inotifywait is useful, and uses less resources than repeating a command. I often run several commands on a command line eg grep something InALogFile|less is that a script ?

Thanks @XTian, a great command. I also now saw in the man page that you can add -m to continually monitor without a loop.

You can create your own repeat command doing the following steps; credits here:

First, open your .bash_aliases file:

Second, paste these lines at the bottom of the file and save:

Third, either close and open again your terminal, or type:

Et voilà ! You can now use it like this:

$ repeat 5 echo Hello World . 

there is a small typo in the line xdg-open ~/.bash-aliases. it should be: xdg-open ~/.bash_aliases (ie: underscore)

Another concern with the «watch» approach proposed above is that it does display the result only when the process is done. «date;sleep 58;date» will display the 2 dates only after 59 seconds. If you start something running for 4 minutes, that display slowly multiple pages of content, you will not really see it.

On the other hand, the concern with the «while» approach is that it doesn’t take the task duration into consideration.

while true; do script_that_take_between_10s_to_50s.sh; sleep 50; done 

With this, the script will run sometime every minutes, sometime might take 1m40. So even if a cron will be able to run it every minutes, here, it will not.

So to see the output on the shell as it’s generated and wait for the exact request time, you need to look at the time before, and after, and loop with the while.

while ( true ); do echo Date starting `date` before=`date +%s` sleep `echo $(( ( RANDOM % 30 ) + 1 ))` echo Before waiting `date` after=`date +%s` DELAY=`echo "60-($after-$before)" | bc` sleep $DELAY echo Done waiting `date` done 

As you can see, the command runs every minutes:

Date starting Mon Dec 14 15:49:34 EST 2015 Before waiting Mon Dec 14 15:49:52 EST 2015 Done waiting Mon Dec 14 15:50:34 EST 2015 Date starting Mon Dec 14 15:50:34 EST 2015 Before waiting Mon Dec 14 15:50:39 EST 2015 Done waiting Mon Dec 14 15:51:34 EST 2015 

So just replace the «sleep echo $(( ( RANDOM % 30 ) + 1 )) » command with what ever you want and that will be run, on the terminal/shell, exactly every minute. If you want another schedule, just change the «60» seconds with what ever you need.

Shorter version without the debug lines:

while ( true ); do before=`date +%s` sleep `echo $(( ( RANDOM % 30 ) + 1 ))` # Place you command here after=`date +%s` DELAY=`echo "60-($after-$before)" | bc` sleep $DELAY done 

Источник

Как запустить команду несколько раз в Linux

По той или иной причине вы можете захотеть запустить команду несколько раз в Linux. В этом руководстве мы обсудим некоторые распространенные и эффективные способы достижения именно этого. Рассмотрим первый способ.

Обратите внимание, что если вы собираетесь запускать команду за командой через каждые x секунд, вы можете проверить – Как запускать или повторять команду Linux каждые X секунд

Запустите команду несколько раз в Linux, используя Bash for Loop

Самый простой способ повторить команду в оболочке Bash — запустить ее в цикле. Вы можете использовать следующий синтаксис, где счетчик является переменной (вы можете дать ему имя по своему выбору, например, i или x и т. д.) и n — положительное число, обозначающее, сколько раз вы хотите, чтобы команда выполнялась:

for counter in ; do yourCommand_here; done
$ for x in ; do echo "linux-console.net - The #1 Linux blog $x"; done

Запустите команду несколько раз в Linux, используя цикл while

Как и в предыдущем методе, цикл while также можно использовать для многократного запуска команды в Linux, используя следующий синтаксис:

$ i=1; while [ $i -le n ]; do yourCommand_here; i=$(($i++)); done OR $ i=1; while [ $i -le n ]; do yourCommand_here; ((i++)); done

В приведенном выше формате i представляет переменную счетчика, [ $i -le n ] — условие проверки, а n — количество раз вы хотите запустить команду (в идеале количество раз, которое оболочка будет выполнять в цикле.

Другой важной частью цикла while является i=&#36 (($i+1)) или (($i++)), которая увеличивает счетчик до тех пор, пока не будет выполнено условие проверки. становится ложным.

Таким образом, вы можете запускать свою команду много раз (замените 10 на количество раз, которое вы хотите повторить команду):

$ i=1; while [ $i -le 10 ]; do echo "linux-console.net - The #1 Linux blog $i";((i++)); done

Запуск команды несколько раз с помощью команды seq

Третьим способом запуска команды несколько раз в Linux является использование команды seq, которая последовательно печатает последовательность чисел в сочетании с командой xargs в следующей форме:

$ seq 5 | xargs -I -- echo "linux-console.net - The #1 Linux blog"

Чтобы добавить счетчик в конце каждой команды, используйте следующий синтаксис:

$ seq 5 | xargs -n 1 echo "linux-console.net - The #1 Linux blog"

Кроме того, проверьте эти связанные статьи:

  • 4 полезных инструмента для запуска команд на нескольких серверах Linux
  • 4 способа просмотра или мониторинга файлов журналов в режиме реального времени
  • MultiTail — одновременный мониторинг нескольких файлов в одном терминале Linux

Это все на данный момент. Если вам известны другие способы многократного запуска команды в Linux, сообщите нам об этом в разделе комментариев ниже.

Источник

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