Way to set date automatically from command line - macos

I make a script in a command line, but I have a problem. I need change date automatically from a command line. Is it possible?
I know, I can use static date for example:
date 0101122315
but I need an automatic date from the internet in macOs.

You've probably got some research to do, here is one possible outline:
Use curl to have the date from the internet and store in a file or send to standard output - in the latter case you may pipe into more commands or store in a shell variable.
If needed: Use sed, awk, grep, some JSON editor, etc. to extract the date from the result of (1). Not needed if your URL just returns the date and nothing else.
Use date and shell variable or command output substitution to pass your date as an argument.
You can find documentation on all the commands, and the shell, using the man command, e.g. man curl.
You might end up with a short one line script (something like:
date `curl URL | sed command`
) or something longer. Nobody can really tell you as it is unstated in the question what the URL will return.
If you get stuck once you're further along ask a new question showing what you've developed and explains the error and someone will undoubtedly help you progress.
Have fun!

Try this command
sudo sntp -sS time.apple.com

Related

Prompt command, but for shell scripts [duplicate]

I want to print the date after every bash command I run.
This could help me understand how much a command took to execute when I am away from keyboard.
I know I could do
`DATE=`date +%d/%m/%Y\ %H:%M:%S` && echo $DATE`
to get the date but I don't know how or even if it could be possible to run this command after every command I execute on bash.
I would also be interested in running the same command before every command so I could know how long a command took.
Is it possible?
What file should I edit?
For example:
$ wget google.com
15/07/2017 23:40:05
I would be happy, if I could also introduce this following feauture:
$ wget google.com
15/07/2017 23:40:05 15/07/2017 23:40:11
Program run for 00:00:06
where the first date is when I ran the program, second is when program terminated the third is self-explanatonary.
As you understood, I don't want to type every time
$ wget google.com && `DATE=`date +%d/%m/%Y\ %H:%M:%S` && echo $DATE`
To execute a cmd before every command entered, set a trap on DEBUG. Eg.
trap date DEBUG
To execute that command before emitting a prompt, set PROMPT_COMMAND:
PROMPT_COMMAND=date
This does exactly that:
PROMPT_COMMAND+=$'\n'"date +%d/%m/%Y\ %H:%M:%S"
The string in PROMPT_COMMAND gets evaluated after every command. You just need to add the date command to whatever you already had in it. ($'\n' (newline) is a somewhat more robust joiner than ; as two consecutive ; would give you a syntax error)
You can add date/time to your prompt, via PS1 variable. You could use date command, but it's more efficient to use the supported special characters, like \d for date, or \D{strftime-fmt}.
For example:
PS1='\u#\h[\D{%F} \D{%T}]\w\$ '
or, with color:
PS1='\[\033[01;32m\]\u#\h\[\033[00m\][\[\033[02;33m\]\D{%F}\[\033[08m\]T\[\033[00m\]\[\033[02;33m\]\D{%T}\[\033[00m\]]\[\033[01;34m\]\w\[\033[00m\]\$ '
will show:
user#host[2017-07-16 00:01:17]~/somedir$
Note that in the second case (with color) we have a valid ISO8601 timestamp, with a "hidden" date/time separator T in the middle. If you select it with a mouse, T is visible and can be copied. (Also double-click will select the complete timestamp, not only date or time.)
To print timestamp after every command just modify your PS1 prompt and add date to it. The only catch here is that it will tell you time when command ended and new prompt showed. So in case you have your prompt open for long time just hit enter to capture start time before running your command.
PS1="\D{%F %T} \$ "
See this arch wiki page or just google bash prompt customization.
To add time spent executing program just add time before the command
$ time wget google.com
It will give you output like this
real 0m0.177s
user 0m0.156s
sys 0m0.020s
And you can get even more lazy and for commands that you dont't feel like typing time every time you run it, just create alias.
alias wget="time wget"
Because in bash aliases are run before other commands you can do it this way even if it looks like recursion. Then you will call it as you are used to.
And of course, aliases and prompt settings can be put in your .bashrc file, so you don't have to type them every time you open terminal.

Setting the current date into a variable in a Script in bash

So for the life of me I cannot figure out why my script will not take my date command as a variable. I have a script that is run every time a message is received and procmail filters specific messages by their subject line. The script looks like this:
d=$(date +%Y%m%d)
:0 wc
* ^(From|subject).*xxx
| cat&>/xx/xx/xx/xx/MSG:$d && \
chmod xxx /xx/xx/xx/xx/MSG:$d && \
/xx/xx/xx/otherscript.sh /xx/xx/xx/xx/MSG:$d
I have run the date command plenty of times in other scripts and to stdout without any issue, so I am wondering if this is a procmail issue? I have looked at a few different sites about this but still have not found a solution. My end goal is to create unique file names as well as for organization purposes each time a new email comes in.
The other reason for me believing it has something to do with procmail is that it was working fine just 3 months ago (didn't change any files or permissions). I have even tried several variations (only showing a few examples):
$'date +"%Y%m%d"'
$(date)
echo $(date)
I get a variety of files created ranging with it printing MSG:(date), MSG:(date ,etc. MSG:(date appears to like it tries to read the variable but is getting cut off or the space between date and + is causing an issue.
And at the end of my script I send it to another script which also creates a new file with the date appended and it works just fine:
fileOut="/xxx/xxx/xxx/xxx.$v.$(date +"%Y%m%d-%H%M%S").xxx"
prints: xxx.YH8AcFV9.20160628-090506.txt
Thanks for your time :-)
Procmail does not support the modern POSIX shell command substitution syntax; you need to use backticks.
d=`date +%Y%m%d` # or just date +%F
If you want to avoid invoking an external process, the From_ pseudo-header contains a fresh date stamp on many architectures.

Getting date month in english format inside bash script

In a bash script I have the following:
MES=$(date +"%b")
How can I get the month in english format?
Now if I echo $MES variable, I get abr. But I would like to get apr.
I'm trying to solve this without using if statement or switch. May be is an option...
I have tried date -u but is not working for me.
EDIT:
Finally I have put this line in the first line of script script:
#!/bin/bash
LANG=en_us_8859_1
# Here rest of the script
Now is working, but I can't accept my own answer as valid... I think because I haven't enough reputation in stackoverflow
Use Command Substitution
MES=$(LANG=en_us_88591; date +"%b")
to change the language just for this single call.

Converting a history command into a shell script

This is sort of one of those things that I figured a lot of people would use a lot, but I can't seem to find any people who have written about this sort of thing.
I find that a lot of times I do a lot of iteration on a command-line one-liner and when I end up using it a lot, or anticipate wanting to use it in the future, or when it becomes cumbersome to work with in one line, it generally is a good idea to turn the one-liner into a shell script and stick it somewhere reasonable and easily accessible like ~/bin.
It's obviously too cumbersome to use any sort of roundabout method involving a text editor to get this done, and it's possible to simply do it on the shell, for instance in zsh typing
echo "#!/usr/bin/env sh" > ~/bin/command_from_history_number_523.sh && echo !523 >> ~/bin/command_from_history_number_523.sh
followed by pressing Tab to inject the !523rd command and somehow shoehorning it into an acceptable string to be saved.
This is particularly cumbersome and has at minimum three problems:
Does not work in bash as it does not complete the !523
Requires some manual inspection and string escapement
Requires too much typing such as the script name must be entered twice
So it looks like I need to do some meta shell scripting here.
I think a good solution would function under both bash and zsh, and it should probably work by taking two arguments, an integer for the history command number and a name for the shell script to poop out in a hardcoded directory which contains that one command. Furthermore, under bash, it appears that multi-line commands are treated as separate commands, but I'm willing to assume that we only care about one-liners here and I only use zsh anyway at this point.
The stumbling block here is that i think I'll still be running shell scripts through bash even when using zsh, so it won't likely then be able to parse zsh's history files. I may need to make this into two separate programs then.
Update: I agree with #Floris 's comment that direct use of the commands like !! would be helpful though I am not sure how to make this work. Suppose I have the usage be
mkscript command_number_24 !24
this is inadequate because mkscript will be receiving the expanded out contents of the 24th command. if the 24th command contains any file globs or somesuch they will have been expanded already. This is bad, and I basically want the contents of the history file, i.e. the raw command string. I guess this can be worked around by manually implementing those shortcuts in here. Or just screw it and just take an integer argument.
function mkscript() {
echo '#!/bin/bash' > ~/bin/$2
history -p '!'$1 >> ~/bin/$2
}
Only tested in Bash.
Update from OP: In zsh I can accomplish this with fc -l $2 $2

linux bash script: set date/time variable to auto-update (for inclusion in file names)

Essentially, I have a standard format for file naming conventions. It breaks down to this:
target_dateUTC_timeUTC_tool
So, for instance, if I run tcpdump on a target of 'foo', then the file would be foo_dateUTC_timeUTC_tcpdump. Simple enough, but a pain for everyone to constantly (and consistently) enter... so I've tried to create a bash script which sets system variables like so:
FILENAME=$TARGET\_$UTCTIME\_$TOOL
Then, I can just call the variable at runtime, like so:
tcpdump -w $FILENAME.lpc
All of this works like a champ. I've got a menu-driven .sh which gives the user the options of viewing the current variables as well as setting them... file generation is a breeze. Unfortunately, by setting the date/time variable, it is locked to the value at the time of creation (naturally). I set the variable like so:
UTCTIME=$(/bin/date --utc +"%Y%m%d_%H%M%Z")
What I really need is either a way to create a variable which updates at runtime, or (more likely) another way to skin this cat.
While scouring for solutions, I came across a similar issues... like this.
But, to be honest, I'm stumped on how to marry the two approaches and create a simple, distributable solution.
.sh file is posted via pastebin, here.
Use a function:
generate_filename() { echo "${1}_$(/bin/date --utc +"%Y%m%d_%H%M%Z")_$2"; }
And use it like this:
tcpdump -w "$(generate_filename foo tcpdump).lpc"
It's hard to get the function to automatically determine the command name. You can use bash history to get it and save a couple of characters typing:
tcpdump -w "$(generate_filename foo !#:0).lpc"

Resources