saving cron job in ubuntu [closed] - cron

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am new to ubuntu and cron job. I have entered the following into my command line:
crontab -e
and I get the following output: "no crontab for teddy - using an empty one 888"
Then I enter when I want it to execute (I believe this is right?... I want it to run once a day, everyday at 8pm):
00 18 * * * /*****/*****/****/test.php
Here is my problem, I dont know how to exit back to the command line. Everything I type gives me weird looking letters and enter (return) doesn't do anything. I have read that this will do the job
ESC : w q
but its not working for me. I tried typing that in, I tried pressing them at the same time, I tried pressing one at a time. Nothing, still stuck. When I press ESC, it comes out as ^[.
This is probably very easy question and I apologize if it is stupid but I have been stuck for sometime. Any help would much appreciated.
Thank you
P.S. I read somewhere that if this is your first job that you need to to do an end line at the end of the cronjob... is this a simple enter key press or actually typing \n?

Teddy13, let's get some clarifications here.
Ubuntu is the distribution of Linux you are using. None of the commands you're typing are exclusive to Ubuntu.
You're asking questions about two separate issues. One is "How do I write a crontab". The other is "How do I use vi, the default editor of the crontab command".
First, man crontab to review the format for entries in the file. Note that cron runs things that are executable from the shell. You can only run your "test.php" script if it is structured like a shell script, with the first line containing "shell magic" (i.e. something like #!/usr/local/bin/php).
Second, while vi is a powerful and well-loved text editor, it's not the easiest to use. I fully support any efforts you may make to learn how to use it, but until you're comfortable with it, you might want to consider switching to "pico" or "ee" or "joe", which are all much easier to learn, though they can do much less. You can install joe, for example, with the command: apt-get install joe run as root. Then to use joe to edit your crontab, add export VISUAL=/usr/bin/joe to the .bashrc file in your home directory.
There's a lot of background information you may want to get. Read lots. It's worth it.
UPDATE (per comment):
Here's the basic stuff you need to edit your crontab.
crontab -e ... as you now know, this edits your crontab file using $EDITOR or $VISUAL, which defaults to vi.
Inside vi, you are always in one of three modes. MOVEMENT mode lets you move around the file using arrows or H, J, K and L. You can delete lines with "dd" or characters with "x". EDIT mode lets you add or change text. From Movement mode, use "i" or "a" or "o" to enter Edit mode in different ways. Read docs for details. Third, COMMAND mode can be reached by hitting ":" from Movement mode. From here, you can issue a variety of commands to save, search, bulk edit, etc.
From Movement mode, you can save your file and exit using "ZZ". From edit mode, you can do this with the command "wq" (hence the ":wq" mentioned elsewhere).
Alternately, you can set a new crontab by piping information into the crontab command. Note that this will erase any existing crontab you may have. Run this in your shell updating the URL of your script as required:
echo "0 20 * * * wget http://example.com/path/to/file.php" | crontab -
crontab -l will show you what your current crontab contains.
Hope this helps.
UPDATE #2 (per comments below):
$ tmpfile=/tmp/foo.$$
$ crontab -l > $tmpfile
$ echo "30 6 * * * Mail -s wakeup pager#example.net <<< 'Time to wake up.'" >> $tmpfile
$ crontab - < $tmpfile && rm $tmpfile

You can try Ctrl+X. This will ask you for changes to save or not before exit. In that just give Shift+Y so you will get out of there. Try it.

You need to press ZZ to exit (upper case 'z' twice) . Here is an article on setting up cron tabs - http://www.sophos.com/support/knowledgebase/article/12176.html

Related

Crontab on linux [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I can't understand, I have looked at several forums to help me, etc... But it still doesn't work!
I would like to run a script thanks to Cron!
To try, I'm currently trying to execute a script that sends "test" in commands (with echo test). No problem, this script works perfectly by hand if I call the file.
But I tried to run my file with Crontab -e every minute and I've been waiting for several minutes already, but no results.
And I can't really understand why!
Already, I was told to put #! /bin/bash at the beginning of my code in my script, but when I put it in I have an error and the code doesn't execute by hand. Whereas if I don't put anything in, the code runs smoothly.
So I don't know if that's where the mistake came from, maybe.....
The final goal would be to make a script that runs every day, say to clear the cache with sync; echo 3 > /proc/sys/vm/drop_caches.
What should look like in the Crontab : 00 20 * * * PATH if I'm not mistaken.
Do you have a solution to help me?
EDIT: -bash: /root/Discord/script/cache.sh: /bin/bash^M: bad interpreter: No such file or directory it's the error I got when I runned /root/Discord/script/cache.sh to execut my script. And that command works when I don't have #! /bin/bash. But that works when I used sh cache.sh in the directory, even with #! /bin/bash !
Crontabs don't print the output on your opened terminal. You need to either create a file and then append the output there to view or test if it works. You can refer this answer https://stackoverflow.com/a/28856563/7181668
But if you want to run a shell script file through cron then you need to make sure you have given executable permission to that file and then you can use the below command in crontab -e
* * * * * /bin/sh /home/myUser/scripts/test.sh

How do I make a script or program to run certain commands? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get into writing scripts that execute in the terminal. I wanted to know what the best way to do this was. I want to start by making a simple script that will run four or five commands that will update a certain program on my computer and have that run every day at a certain time. I have a programming background, but I am unfamiliar with this kind of scripting. I would appreciate any advice or input such as what language to use.
First of all, you need to open a Terminal (such as Terminal, Terminator, etc) and then you run this:
touch myScript.sh
chmod 755 myScript.sh
The first command creates an empty file and then you give 755 permissions to it. It means that it will be readable and executable by any user in your machine. If you need more details about those permissions, you can refer to the documentation here. But, believe me, those permissions will work for the moment.
Now you can insert instructions into the file using several methods: You can open it with a text editor such as vi, etc; Also, you can echo those commands this way:
echo "ls /tmp" >> myScript.sh
echo "echo 'hello'" >> myScript.sh
echo "pwd" >> myScript.sh
If you open that file, you can find that it is simply a list of commands one at each line. Then, when you run the script, each command will be executed in order from top to bottom.
You can run the script using the following sintax:
./myScript.sh
Voilá!
crontab -e
Then add following line beside the above command:
30 10 * * * script.sh
It will run everyday at 10:30 AM

Cron says "errors in crontab file, cannot install" [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm attempting to execute the following series of commands to create backups of MySQL databases.
When I attempt to add the command to my crontab using crontab -e I get the error "errors in crontab file, cannot install" and asks me if I want to retry.
mkdir /home/mysql-backup/`date '+%m-%d-%Y'`; mysql -s -r -e 'show databases' | while read db; do mysqldump $db -r /home/mysql-backup/`date '+%m-%d-%Y'`/${db}.sql; done; rm -r -f `date --date="1 week ago" +%m-%d-%Y`; du -k |sort -n > output; mail -s "MySQL Backups" "steven#brightbear.net" < output
Is there anything I should be changing in this file? Or should I look into creating a script file and calling that from cron.
Thanks in advance for any assistance you can provide.
If you gave that script to crontab -e of course it will disagree. A line in a crontab file should start with 5 fields indicating when you want the script to run, as can be read in crontab's manpage.
On the other hand, most Linux distros nowadays have preset facilities for things that should be executed hourly (/etc/cron.hourly), daily (/etc/cron.daily), etc. It's a whole lot easier to just put your script in a file in the appropriate directory and it will get executed in the selected time raster. An added advantage is that in these files you won't be forced to cram everything into one line.
Yes; as a matter of style, if nothing else, I encourage to put the SQL commands into a shell script, and then run the shell script from cron.  (And, as Anew points out, the command sequence is easier to maintain/debug if it’s broken out into multiple lines, with comments.)  But –– is that all of what you’re feeding into crontab?  Look at man crontab and add the fields that specify when you want the command to run.
From the crontab(5) man page, it looks like percent signs (%) have a special meaning, so that is probably where you're running into trouble.
Yes, you should put your commands into a separate shell script and just call that from the crontab line. This will also make it much easier to read the crontab file, and you can format your script nicely so that it's easier to maintain. And you can test it separately from the crontab that way.

Bash: call script with customized keyboard shortcuts?

Lets say I have a script, "myscript.sh", with contents being simply echo $PWD. I'd like to bind somehow this script to a key combo in bash (gnome-terminal) - so that when I press this key combination, the output of "myscript.sh" is inserted ("pasted") at the cursor position in the terminal.
Apparently, bash history and line manipulation is handled by readline - and the references I got for bash keyboard shortcuts, do reference readline:
bash keyboard shortcuts
Bash Reference Manual: Bindable Readline Commands
I've also seen in Bash Reference Manual: Readline Init File Syntax that the key bindings for bash can be listed by using bind -p (see help bind [not 'man bind'] for more). So maybe this question would better be titled as "_binding macros to custom keyboard shortcuts in readline" :) But in any case, is what I want possible to do?
I guess an alternative would be to have the script be something like "pwd | xsel -b", and then I call it on terminal - and I can paste afterwards; but I'd still like a single keyboard shortcut instead, say like Ctrl-Alt-H (which seems to be not used for anything), which will immediately insert/paste script output when pressed.
Thanks in advance,
Cheers!
EDIT: Just to clarify - here is my use case where I'd like this facility. I'm usually cd'd in a project folder, usually named something like myproject-folder-0012a, which is under revision control by svn. And there is a bunch of these folders. So quite often, I do commits where the first word of the message is the directory name, as in:
svn ci -m "myproject-folder-0012a: here a commit message"
But that is what I don't like - first I type 11 characters, which go rather fast:
svn ci -m "
And then, I cannot use autocompletion to get the name (i'm inside the folder) - which means I either have to fully type it (no way :)), or I copy paste it from the prompt (which requires selection - press mouse, drag, release mouse; then Ctrl+Shift+C, and then Ctrl+Shift+V, plus any left/right keys if I miss allignment - plus deletions and such if I make the copy wrong).
Meaning - so much work, just to get the bloody folder name for a bloody commit message :( I'd MUCH rather press something like (say) Ctrl-Alt-H, and have the folder name automatically inserted at cursor position, and be done with it :)
My suggestion for xsel is only because I could put it into a "global" script - say symlink it as /usr/bin/myscript (and obviously, the contents of the script are echo $(basename $PWD) rather than just pwd for my needs), and then I could do:
$ myscript # this puts directory name in clipboard
$ svn ci -m "[CTRL+SHIFT+V TO PASTE HERE]myproject-folder-0012a[NOW TYPE]: here a commit message"
... which sort of makes the workload less, but still - then I have to remember what the script name is, and call it, before I type the svn command (and I don't always remember that)... And still - I have to call a command, and then press a key combo; why shouldn't I just press a key combo once, and be done with it ??! :)
Well, hope this clarifies my problem a bit better ....
EDIT2: However, another reason why a bash keyboard shortcut would be useful, is that then I could also "paste/insert current directory name" not only in shell commands - but also in terminal programs, say like nano (where it would, arguably, be more difficult to use bash script or function expansion directly).
Simple version:
This command at a shell prompt:
bind '"\ee": "${PWD##*/}\e\C-e"'
or this line added to your ~/.inputrc:
"\ee": "${PWD##*/}\e\C-e"
will cause Alt-e to insert the basename of the current directory on the command line. It requires that the default binding of the readline function shell-expand-line which is \e\C-e be present (this could be adapted if it's different). I'm also making the assumption that you're using Bash's emacs mode.
Unfortunately, it causes things that have already been typed to be expanded as well. One of the affects of this is that after having typed:
svn ci -m "
and pressing Alt-e, the quotation mark will have disappeared. There are a couple of ways to deal with this.
One, assume that all you'll lose is the quote and either manually add it back or have the readline macro add it for you:
bind '"\ee": "${PWD##*/}\e\C-e\eb\"\C-e"'
which just isn't very satisfactory.
Advanced version:
Or, two, kill the line, do the insertion, then yank the line back:
bind '"\ee": " \C-u \C-a\C-k${PWD##*/}\e\C-e\C-y\C-a\C-y\ey\b"'
or
bind '"\ee": " \C-u \C-a\C-k${PWD##*/}\e\C-e\C-y\C-a\C-y\ey\b\ef\C-f"'
This leaves the rest of the line intact (nothing else is expanded or deleted), but it uses the kill ring, so it may leave it in a state that's different than you expect (if you're using it). It also inserts a space after the inserted directory name (the spaces in the macro are used to ensure that older kill-ring contents are not regurgitated if the macro is executed at the beginning or end of the line). The macro should work regardless of the position of the cursor in the line. The insertion will be made at the cursor's position, leaving the cursor in the same position [in the first version].
Edit: The second version leaves the cursor after the dirname and space that are inserted.
Edit 2:
The readline function shell-forward-word (unbound) does a better job than forward-word (\ef) for this. You can make use of that like this:
bind '"\ew":shell-forward-word'
bind '"\ee": " \C-u \C-a\C-k${PWD##*/}\e\C-e\C-y\C-a\C-y\ey\b\ew\C-f"'
By the way, you should know that Bash keyboard shortcuts are not active in other programs such as nano.
Ok, not really an answer, but I'd just like to summarize the comments I got so far, which are useful for my problem. However, the question as it stands - in respect to bash keyboard shortcuts running arbitrary scripts - is still not answered (I'd still prefer doing all this with a single key combo :))
First, I can use a 'global' script like:
$ sudo bash -c 'cat > /usr/bin/bpwd <<EOF
#!/bin/bash
basepwd=\$(basename \$(pwd))
echo -n \$basepwd # suppress line ending
# exec 1>/dev/null # debug: redir stdout to null
echo -n \$basepwd | xsel -i -b # suppress LF, and make xsel read from stdin
# exec 1>/dev/tty # debug: restore stdout
EOF
chmod +x /usr/bin/bpwd'
Or, I can add bash functions to my .bashrc (note: make sure you reload bash after you add these lines to .bashrc - for example, simply by typing bash in your current terminal):
$ echo '
bpwd2() { basepwd=${PWD##*/} ; echo -n $basepwd | xsel -i -b ; echo -n $basepwd ; }
svnci-test() { echo -n "$(bpwd2): $*" ; }
svnci-m() { svn ci -m "$(bpwd2): $*" ; }' >> ~/.bashrc
Basically, I misunderstood Reese Moore's suggestion originally - you can indeed use backticks - consider this command session (after the above commands have been ran):
$ bpwd
Desktop\
$ bpwd2
Desktop\
$ echo `bpwd`
Desktop
$ echo "`bpwd2` 2"
Desktop 2
This is what I needed to understand Moore's "the output from the backticked commands will be used as input on the executed command" (however, one also needs to take care to clean the line endings from the output); or, in my case, I can call
svn ci -m "`bpwd`: my message here"
# svn ci -m "${PWD##*/}: my message here" # alternatively
... or, I could follow camh's suggestion, and use svnci-m as a function (in my case, I almost never use additional arguments to svn ci, and so my version is slightly different). And to test whether arguments are passed correctly, I can use the svnci-test function:
$ svnci-test "my message"
Desktop: my message\
Thanks for the comments so far,
Cheers!
One way to do what you want with a single key press is to take advantage of programmable completion in bash. You possibly have some programmable completion set up with the bash_completion tool/package. If not, look into that to see the specifics of how it is done.
The idea is to have the programmable completion recognise when you have hit at the start of a svn commit message and then have it return a single completion which is the text you want to insert (the basename of the current directory).
I've only dabbled with programmable completion so I can't give you the details, but the above-mentioned bash_completion package or the subversion completion script may be a good start.

Alternative to Up Arrow + Enter to run previous command?

Sometimes I have to run a command many times in succession, for example to see if a service has started, and it becomes tedious to move my hands away from my normal typing position to press the Up Arrow and Enter keys repeatedly. Is there a way to run the previous command without the Up Arrow and Enter keys, perhaps with an elaborate shell script?
I've tried the following, but it is unsatisfactory because it cannot execute aliases, and it is a little slow.
history | tail -2 | head -1 | cut -d' ' -f4- | cat > prev_command.txt
sleep .01
chmod 777 prev_command.txt
eval prev_command.txt
rm prev_command.txt
Ideally I'd have an alias to this script so I can type in something like "prev" in the command line and hit Enter to run the previous command again.
In bash, you can press ctrlp to go to the previous command -- that's a lot better than having to move to the arrow keys.
See also: https://github.com/fliptheweb/bash-shortcuts-cheat-sheet/
Use
!!
to run your previous command.
sudo !!
also works , for the record.
Instead of running the same command many times in succession, why not watch it instead? watch will run a specified command repeatedly and display the output in stdout so you can see it change over time.
watchcommand
I often use the "history expansion" feature in bash (usually activated with cntlR) -- it interactively searches through your history for the previous closest match.
See the bash manual section Searching for Commands in the History, and also Using History Interactively.
Are you an emacs or vi user? You can use
set -o vi
set -o emacs
to set emacs or vi keybindings. You can then use the emacs or vi key bindings in bash. I don't know if this should work for other shells. I believe the vi mode starts in insert mode, so you need to hit esc to enter command mode. In emacs mode (the default), you can use ctrl+p and then ctrl+j to move to the previous line and do a carriage return.
Otherwise, you can use !! as someone else suggested.
In bash:
$ help fc
fc: fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]
Display or execute commands from the history list.
fc is used to list or edit and re-execute commands from the history list.
FIRST and LAST can be numbers specifying the range, or FIRST can be a
string, which means the most recent command beginning with that
string.
Options:
-e ENAME select which editor to use. Default is FCEDIT, then EDITOR,
then vi
-l list lines instead of editing
-n omit line numbers when listing
-r reverse the order of the lines (newest listed first)
With the `fc -s [pat=rep ...] [command]' format, COMMAND is
re-executed after the substitution OLD=NEW is performed.
A useful alias to use with this is r='fc -s', so that typing `r cc'
runs the last command beginning with `cc' and typing `r' re-executes
the last command.
Exit Status:
Returns success or status of executed command; non-zero if an error occurs.
Note the suggestion for alias r; I use this frequently.
Depending on what terminal you're using, I know a lot used to have F3 as an option for repeating, but that's still outside the normal range for typing as well unless you have a special keyboard with more accessible function keys.
My keyboard makes the function keys easily accessible, but I don't do much command line work in unix any more, so I wouldn't be able to tell you for sure whether or not this is still possible.

Resources