Editing WSL2 instance of Ubuntu Crontab using Windows VSCode - visual-studio-code

My question is whether it is possible to edit the crontab of a WSL2-based instance of Ubuntu with my Windows VSCode that is connected via WSL remote SSH.
If I type export EDITOR=code inside my WSL instance and then crontab -e, I am able to see a /tmp/crontab.sygFAU file load inside my VSCode instance.
The problem is that once I make edits to this file, it will save the file to /tmp/crontab.sysFAU but it doesn't actually take the next step of replacing the the real crontab file in /var/spool/cron/crontabs.
So once I re-open the crontab, it will just show what I had previously, and not my saved edits.
It would be nice to know if this is not possible or if there are any alternative ways to run a GUI editor because using nano is a pain!

An interesting question that I haven't considered before, myself. Here's what's happening:
You set your editor to code
You crontab -e, which properly loads VSCode with the temporary crontab.
However, because this is a Windows GUI application, it returns control to the parent Linux application (crontab) immediately after starting VSCode. You can see the same result if you just start notepad.exe from your shell in WSL -- Once Notepad starts (rather than exits) control is returned to the shell.
If you switch back to your terminal at this point, you'll see that crontab detected that the editor that it launched exited (returned), and so it has already tried to copy the temporary file to the permanent location.
However, since the temporary files doesn't yet have any changes, crontab decides there's nothing to do.
Editing the file in VSCode and saving it has no effect, other than to leave a dangling /tmp/... file hanging around (since crontab isn't there to clean up).
So what's the solution? We need a way to launch a Windows GUI application and prevent it from returning control to crontab until you are done editing.
I originally thought something from this question might work, but the problem is that the actual command that launches the Windows process is embedded in a shell script, which you can see with less "$(which code)" (or code "$(which code)"), but it's probably not a great idea to edit this.
So the next-best thing I came up with is a simple "wrapper" script around the (already-a-wrapper) code command. Create ~/.local/bin/code_no_fork.sh (could be anywhere) with:
#!/usr/bin/env bash
code $* > /dev/null
echo Press Spacebar to continue
read -r -s -d ' '
Credit: This answer for the Spacebar approach
Then:
EDITOR=~/.local/bin/code_no_fork crontab -e
After you make your edits in VSCode, simply press Space to allow the script to continue/exit, at which point crontab will (assuming no errors were detected) install the new Crontab.
Alternatives
This is should typically only be a problem with Windows GUI applications, so the other possible avenue is to simply use any Linux editor that doesn't fork. If you want a GUI editor, that's entirely possible as long as you are running a WSL release that includes WSLg support (now available for Windows 10 and 11).
I won't offer any individual editor suggestions since that would get into "opinion" and "software recommendation" territory, which is off-topic here.

Related

Weird CMD - VSCode behavior

yesterday I had SumatraPDF and VisualStudioCode with latex-workshop working with forward and reverse-search. Today the reverse-search didn't work any more. With a simple bat file I tried to show the commandline arguments.
echo %*
pause
They seemed correct and when I copied the command and paste it into a new cmd it works. To do further testing I tried to direct command and run it.
"C:\....\Code.exe" -g "%1:%2"
pause
Visual Studio Code responds: bad option -g
In SumatraPDF I set cmd as command.
Now the behavior is that I have two cmd windows. With the cmd directly opened the VSC open's the file. With the cmd launched indirect I got the error message.
I have tried resetting the environment variables, changing the current working directory, and checking the code page currently in use.
How can it be that cmd behaves differently with seemingly the same environment? And what can I do to make a cmd started from an application work like a cmd started by windows?
Update: It appears there were a couple of recent security changes in the way VSCODE.exe is allowed to interact with the command line (especially affecting LaTeX-workshop users) so for recent changes twice this year see the discussion at https://forum.sumatrapdfreader.org/t/inverse-search-not-performed-for-vs-code-exe/4486/27
Within SumatraPDF the reverse syntex command for %1 is replaced by %f for file and (l)L for line
It is triggered by a double click near the line of interest and if the synctex index file was compiled correctly by PdfLaTeX (or similar) it will include the tex %f(ilename) and the nearest %l(ine) reference to the point where double clicked.
Thus your tex syctex enhanced "reverse search" call out of SumatraPDF should historically be
"C:\...path to...\Code.exe" -g "%f:%l"
that's Lower L not 1
Avoid using any depreciated -inverse-search parameter from a LaTeX editor just add it once into SumatraPDF-settings.txt and then it's not disturbed by repeated assignments when running your -forward-search.
It will NOT work if the file.synctex or file.synctex.gz is corrupt by a bad PDF compilation.
HOWEVER It seem Microsoft have added the requirement to add a CLI.js handler and requires another switch setting after that ! (see link to discussion in Update above)
For a small test file download https://github.com/GitHubRulesOK/MyNotes/raw/master/AppNotes/SumatraPDF/LATeX%20and%20Reverse-Search.zip unpack and open sync.pdf in SumatraPDF to test that double click on page opens sync.tex in the editor
If the message is cannot start ... then the command line is not configured correctly. A rough test for a bad synctex is to see what happens if the call is changed by adding cmd /k echo to the start, since that will confirm the reverse command. Here I wrote "wrong" as the path to code.exe, once corrected I can remove cmd /k echo.
For some other systems where the reverse might change
see https://github.com/sumatrapdfreader/sumatrapdf/issues/1197#
However there should be no interference in a valid VsCode call.

Redirect WSL input in Powershell

I've been trying to write a powershell script that automates my windows workspace setup and configuration and am currently stuck trying to redirect input to WSL when executing it for the first time. The core of the problem is that Ubuntu's first launch prompts for a username and password, then logs in to a bash shell. I tried writing down the input lines into a text file like so:
Username
Password
Password
exit
Then, I tried redirecting the input of wsl to the file:
Start-Process ubuntu2004.exe -RedirectStandardInput stdin.txt -NoNewWindow -Wait
The above didn't work as executing WSL just starts spamming Enter new UNIX username: adduser: only one or two names allowed. I tried doing same in CMD with the < input redirection, but the result is the same.
This is not exactly the answer to your question, but in my opinion, ansible is better suited for such a task.
I myself recently became interested in assembling a workspace in wsl and ansible seemed to me the best solution.
Before starting the build, you will need to perform minimal steps (create a user and install several packages, all this can be placed in the readme), but then there will be no restrictions.
You can find several ready-made examples of wsl assembly via ansible on github.
A few ideas for setting the username/password in a new Ubuntu WSL instance:
First, a "PowerShell sendkeys" via COM or Interop might work for this. It's probably the closest in behavior to what you are actually asking.
Second, and perhaps most promising, I just tried this with a new Debian WSL installed from the Store (since I didn't want to mess with my Ubuntu install).
When running debian.exe (like ubuntu2004.exe), I let it run the install, then I Ctrl+C'd out of it when it started asking for the default username/password. At that point, the WSL instance is installed, but with only root. I assume that your script can let the command run for a certain period of time, then kill the process to replicate this.
From your script, you should then be able to run wsl -u root useradd --create-home --user-group --groups adm,dialout,cdrom,floppy,sudo,audio,dip,video,plugdev,netdev --password "encryptedPassword" username (see here for creating the encrypted password). I think that will get you a stock Ubuntu user the way that WSL sets it up.
You'll then need to either create a /etc/wsl.conf file (instructions) letting the instance know that that user is the default, or LxRunOffline lists this as one of its features.
But I'd also throw in that you might just want to keep a "backup" of an existing WSL instance that you start from. Do a wsl --export <distroname> <imagename.tgz>, then you can import it when setting up the new Windows host by copying the tgz over and doing a wsl --import <DistroName> <DirectoryWhereYouwantItToLive> <imagename.tgz>.
If you want, you can keep this image up to date with your desired WSL configuration, so that you don't have to recreate it when you rebuild the Windows hosts. That said, this is where I do follow #Mystic's suggestion of using Ansible to store my WSL "configuration as code". It allows me to not only recreate my WSL instances, but also that same configuration when I set (or reset) a Linode host or another Linux system.

Broke my terminal with a bad PATH [duplicate]

This question already has an answer here:
Wrong path set and now .bashrc throws errors [duplicate]
(1 answer)
Closed 6 years ago.
I put an invalid path into my bashrc and now my terminal doesn't work. I've deleted my bash_profile as well as my bashrc and I still can't get it to work.
Every command I use in terminal gives me the error:
sh: parse_git_branch: command not found
This was something I had in my bash_profile for git autocompletion. The problem is once I've deleted the files using /bin/rm <file>, I can't apply my changes with source ~/.bash_profile because it's giving me errors. I've looked at this question, and this question, but I still am having no luck.
How can I fix my command line after breaking things like this?
You can export a correct PATH in your current session using a command similar to :
export PATH=/usr/local/bin:/usr/bin:/bin
After using this, you should be able to source your bashrc.
You can always change your path right on the command line for the rest of the current shell session: PATH="/usr/local/bin:/usr/sbin:/usr/bin:/bin:/sbin:"
Exporting the PATH won't solve your problem. It will only export the value of PATH to child shells/processes. This only achieves the same thing as resetting/changing the PATH variable from the command-line (as shown above), because your scope is limited to the current shell process (and its children) while you are working within that shell environment (working from the command-line). If you open a new terminal (start a new login shell, which is a parent process), bash will still be trying to read from the resource files (.bash_profile and .bashrc), which no longer exist.
So, we need to be able to widen our scope and tell bash that we want to make changes for all future bashes (shell processes--new shells, shells within shells, etc.), and the way that is done is by writing those statements in the resource files.
Once you set your PATH there, every shell session will spawn with those resources (all the aliases, commands, variables, and functions stored in those files), loaded, regardless of whether you export it or not, since each shell process will always consult those files before it does anything else (so they effectively pre-emptively import what you are trying to export to them).
bash is like any other script or program. You took away all its inputs and pointers and shortcuts, and now its just been made pretty dumb, so you've got to be explicit with everything you do till you can teach it where to look for stuff (give it a PATH to search) and shorten your conversations with it.
If you don't have a backup of your .bash_profile, here's one that you can use:
# This loads in the configuration in .bashrc
# Put all configuration in there!
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
And here's a .bashrc that can get you started:
export PATH="/bin:/sbin:/usr/local/bin:/usr/bin:/usr/sbin:"

Associate .pl with Perl.exe [duplicate]

I want my Perl scripts to behave just like any other executable (*.exe file).
When I double-click on myscript.pl I want it to execute instead of opening in a text editor.
I want to run myscript.pl instead of perl myscript.pl.
I really want to run myscript instead of myscript.pl.
I want to run program | myscript instead of program | perl myscript.pl.
I want to be able to run my script via drag & drop.
There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.
Related questions:
How do I make Perl scripts recognize parameters in the Win32 cmd console?
Running a perl script on windows without extension
Perl execution from command line question
How can I read piped input in Perl on Windows?
Perl on Windows, file associations and I/O redirection
How do I create drag-and-drop Strawberry Perl programs?
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.
Associate *.pl files with perl
Run the following commands at a shell prompt:
assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.
Default install locations are:
ActivePerl: C:\Perl
Strawberry Perl: C:\Strawberry
Add .PL to your PATHEXT environment variable.
This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.
You can set it for the current cmd session
set PATHEXT=%PATHEXT%;.PL
To set it permanently (under Windows Vista or Windows 7)
setx PATHEXT %PATHEXT%;.PL
Under Windows XP you have to use the GUI:
Right-click My Computer, and then click Properties.
Click the Advanced tab.
Click Environment variables.
Select PATHEXT, then click Edit.
Append ;.PL to the current value.
Make I/O redirection work
I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.
Start Registry Editor.
Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
On the Edit menu, click Add Value, and then add the following registry value:
Value name: InheritConsoleHandles
Data type: REG_DWORD
Radix: Decimal
Value data: 1
Quit Registry Editor.
Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.
See also:
STDIN/STDOUT Redirection May Not Work If Started from a File Association
Perl Scripts on Windows 10 run from Explorer but not Command Prompt
If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.
Add a drop handler
Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:
use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
"DropHandler/" => {
"/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};
Convert your perl scripts into batch files using pl2bat once they are ready to be run by users.
The trick works through the perl -x switch which, according to perldoc perlrun, makes Perl search for the first line looking like #!.*perl.
After following the instructions in the accepted answer, a double click still led to .pl files opening with Notepad in Windows 10 — even when perl.exe was set as the default file handler.
After finding Jack Wu's comment at ActivePerl. .pl files no longer execute but open in Notepad instead I was able to run perl scripts on double-click as such:
Select and right-click a .pl file
Use the "Open With" submenu to "Choose another app"
Select "Always use this app to open .pl files" (do this now – you won't get the chance after you have selected a program)
Scroll to the bottom of the "Other options" to find "More apps", and select "Look for another app on this PC"
Navigate to C:/path/to/perl/bin/ and select Perl5.16.3.exe (or the equivalent, depending on which version of Perl you have installed: but not Perl.exe)
Then the Perl icon appears next to .pl files and a double-click leads to them opening in Perl every time, as desired.
I tried the assoc and ftype methods and they didn't work for me.
What worked was editing this registry key:
Computer\HKEY_CURRENT_USER\Software\Classes\Applications\perl.exe\shell\open\command
It was set to:
"C:\Perl64\bin\perl.exe" "%1"
When it should be:
"C:\Perl64\bin\perl.exe" "%1" %*
It is the same content as the ftype, but for arcane windows reasons, I had to set it there too.
Like some others, I had set 'assoc' and 'ftype', but also had set Notepad text editor via the GUI, and when I tried to execute a script via the command line, Windows invoked Notepad to edit the script instead of running my script.
Using the GUI to instead point the .pl file association to the script-running executable was not much of an improvement, since it would invoke the executable on my script, but would pass no command-line arguments (even when I invoked my script from the command line).
I finally found salvation here which advised me to delete some registry keys.
Key quote:
"The problem is that if you have already associated the program with the extension via the Open With dialog then you will have created an application association, instead of a file extension association, between the two. And application associations take precedence."
In my case, following the instructions to use RegEdit to delete
HKEY_CLASSES_ROOT \ Applications \ perl.exe
where perl.exe is the name of my Perl executable, and then also deleting:
HKEY_CLASSES_ROOT \ .pl
seemed to solve my problem, and then (after re-executing 'assoc' and 'ftype' commands as shown in other answers) I could then execute scripts from cmd.exe and have them run with access to their command-line parameters.
Some other related information here.

Cygwin - run script silenty from "run command"

I have script lets say:
C:\foo.bsh
I want to be able to run this command via the windows run command:
Start -> Run
Windows Key + R
and type something small like 'foo' and hitting return.
However, I do not want a cmd prompt to be visible. This script does some preprocessing for an IDE. I do not want the cmd prompt to be open for the lifetime of the IDE process.
I have tried:
1) Creating a bat file with the following contents:
c:\cygwin\bin\bash --login "C:\foo.bsh" (this fails because it keeps a cmd open)
2) Converting the above bat file to an exe using bat_2_exe_converter (does not make the cmd silent)
thoughts?
EDIT: The solution so far suggests something to type from an actual cygwin shell. I am trying to get a faster solution by having something short I can type in the Windows run command. Also, the nohup command; exit doesn't automatically kill the box - however I can manually kill it without killing the IDE process. The run command accepts shortcuts (.lnk's), bat's, exe's.
Try the run.exe command of cygwin. It is a big install, a complete unix environment for your Windows machine. Suppose you installed it at c:\cygwin\.
No mystery, just run c:\cygwin\bin\run.exe <your command here> and you will have your no dos window execution.
You can run it from any DOS window (run cmd.exe from the start menu). You don't need to run it from cygwin.
To make it easier, append C:\cygwin\bin to your %PATH% env var (My Computer → Properties → Advanced → Environment Variables) (Kudos to Felipe Alvarez comment).
Now you can just type
c:\cygwin\bin\run.exe "C:\foo.bsh"
You must create a link in your Start Menu with this command so will be able to run it with Win-R.
Here is the man page of the runcommand:
$ man run
RUN(1) run 1.3.0 RUN(1)
NAME
run - start programs with hidden console window
SYNOPSIS
run [ -p path ] command [ -wait ] arguments
runcommand [ -p path ] [ -wait ] arguments
DESCRIPTION
Windows programs are either GUI programs or console programs. When
started console programs will either attach to an existing console
or create a new one. GUI programs can never attach to an exiting con‐
sole. There is no way to attach to an existing console but hide it if
started as GUI program.
run will do this for you. It works as intermediate and starts a pro‐
gram but makes the console window hidden.
With -p path you can add path to the PATH environment variable.
Issuing -wait as first program argument will make run wait for program
completition, otherwise it returns immediately.
The second variant is for creating wrappers. If the executable is
named runcommand (eg runemacs), run will try to start the program (eg
emacs).
EXAMPLES
run -p /usr/X11R6/bin xterm
run emacs -wait
runemacs -wait
run make -wait
AUTHORS
Charles S. Wilson
Harold L Hunt II
Jehan Bing
Alexander Gottwald
Version 1.3.0 November 2005 RUN(1)
You can use either...
c:\cygwin\bin\bash -l /path/to/script_to_interpret.sh
...or...
c:\cygwin\bin\bash -l -c /path/to/executable_script.sh
Note: the -l flag tell bash to "act as if it had been directly invoked by login" and use Bash Startup Files. This is important in that it sets your $PATH and other things you rely on when you launch a cygwin terminal. If you don't include -l or --login you will get "command not found" when you try to call anything except of a bash builtin.
The difference between the 2 is like the difference between doing...
bash script_to_interpret.sh
...and...
./executable_script.sh
...in *nix. The former interprets the script using bash. The latter executes the script (only if it has chmod +x executable_script.sh) and interprets it according to its "shebang" line. The latter method is also what you want to do if your executable is not a script at all, like a *nix binary compiled from source.)
It has been bugging me for a while I couldn't find the solution for this, but I finally got the right mix together.
You can simply do the following if you have cygwin on your PATH:
run bash test.js
If cygwin is not on your path, you can do this:
c:\cygwin\bin\run.exe -p /bin bash test.js
If you are looking for more control over the created window (maximize, etc) it looks like you can use cygstart also.
Sources:
- neves answer above (though that wasn't enough by itself for me personally to figure it out)
- http://cygwin.com/ml/cygwin/2008-09/msg00156.html
As the terminal can't close while your script is still running, try the command:
"nohup C:\foo.bsh; exit"
This way your script will be backgrounded and detached from the terminal, and it should exit quickly so the terminal goes away. I think that the window may still 'flash' with this approach, but the results should be better than what you're getting.
I'm running Cygwin64 and the xwin server link points to:
C:\cygwin64\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe
This creates an icon AND a notification on the taskbar. I don't like that. The icon is rather useless, the notification has all your menu options from .XWinrc.
So... I wrote a .vbs script to silently run this command and make the icon go away:
Set objShell = CreateObject("WScript.Shell")
objShell.Run("C:\cygwin64\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe"), 0
Another imperfect possibility is to run the script via a shortcut and set the shortcut's Run option to "minimized".
Go to the directory where you have installed cygwin(on my machine it is c:/cygwin64/bin)
Once there simply type "bash.exe"