Is There Any Shortcut to Reference the Path of the First Argument in a Mv Command

Is there any shortcut to reference the path of the first argument in a MV command?

You can use history expansion like this:

mv app/modules/keywords_builder.rb !#^:h/keywords_generator.rb
  1. ! introduces history expansion.
  2. # refers to the command currently being typed
  3. ^ means the first argument
  4. :h is a modifier to get the "head", i.e. the directory without the file part

It's supported in bash and zsh.

Docs:

  • bash history expansion
  • zsh history expansion

Move All Files from all Subfolders to Parent Folder using batch script

The best solution is using just one batch file stored in a directory of user´s choice and use a shortcut file in the SendTo folder to run the batch file for a folder of user´s choice by clicking with secondary (usually right) pointing device (mouse) button on a folder in Windows File Explorer to open the context menu and clicking with primary (usually left) pointing device button in submenu Send to on the menu item according to file name of the shortcut file.

1. Batch file for file movement

There can be created a batch file %USERPROFILE%\MoveFilesToFolder.cmd with the following single command line:

@if not "%~1" == "" for /F "delims=" %%I in ('dir "%~1\*" /AD-L /B /S 2^>nul') do @move "%%I\*" "%~1\"

The two @ left to the commands if and move are just for avoiding the output of the parsed command lines before execution which is done in a multi-line batch file with @echo off at top of the batch file.

The IF condition evaluates to false if the batch file is started without passing an argument string to the batch file or with passing just "" to the batch file (empty argument string) like on double clicking on the batch file itself. That condition makes sure not doing anything on batch file started without the required folder path as first argument string.

The for /F loop results in starting in background one more Windows command processor in addition to the cmd.exe process which is processing already the batch file with %ComSpec% /c and the command line within ' as additional arguments. So if the Windows is installed into C:\Windows and the batch file was started with "C:\Temp\Development & Test(!)_100%" as first argument string, there is executed in background:

C:\Windows\System32\cmd.exe /c dir "C:\Temp\Development & Test(!)_100%\*" /AD-L /B /S 2>nul

DIR searches

  • in the specified directory C:\Temp\Development & Test(!)_100%
  • only for directories including directories with hidden attribute with ignoring junctions and directory symbolic links because of option /AD-L (attribute directory and not a link)
  • and all its subdirectories because of option /S and
  • outputs all found directories matching the wildcard pattern * (any) in bare format because of option /B which means just folder name with full path because of option /S to handle STDOUT of the background command process.

It is possible that DIR fails to find any matching file system entry because of the specified directory does not have subdirectories at all or the batch file was started with passing a file name instead of a directory name to the batch file. In this case would be output to handle STDERR just an error message by DIR which is suppressed by redirecting the error message to device NUL.

Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.

The Windows command processor instance processing the batch file captures all lines output to handle of STDOUT of background command process and waits for its self-termination before for /F is processing the captured output line by line with ignoring all empty lines.

There is by default split up each non-empty line into substrings using normal space and horizontal tab as string delimiters, then is checked if the first space/tab delimited substring starts with a semicolon (default end of line character) in which case the line is ignored for further processing and otherwise just the first substring is assigned to the specified loop variable and then FOR runs the command(s) in its body.

The captured folder names with full path cannot contain a horizontal tab character and there cannot be a semicolon at beginning of the folder names with full path, but there can be one or more spaces in the fully qualified folder names. For that reason the option delims= is used to define an empty list of string delimiters which results in each folder name is assigned completely to the specified loop variable I.

The command MOVE moves is run with the current folder name and moves nearly all files in that folder to the folder passed to the batch file with first argument string.

The command MOVE does not move files which

  • have the hidden attribute set or
  • are currently opened by an application with sharing access denied or
  • exist already in the destination directory and the user denies overwriting of the file in the destination folder on prompt or
  • exist already in the destination directory and the user confirms overwriting of the file in the destination folder, but the existing file in destination folder has the read-only attribute set.

The usage of the MOVE option /Y would avoid the prompt for the third case with file existing already in the destination folder. But the overwrite prompt appears even with using option /Y on existing file in destination folder with same name as a file in a subfolder has the read-only attribute set. It does not matter which option is chosen by the user on prompt as the read-only file in destination folder is nevertheless not replaced by the file in source folder.

The file movement is done which just updating the file allocation table of the file system of the drive. No file data is copied and deleted.

There could be used on Windows Vista and newer Windows client versions and on Windows Server 2003 and newer Windows server versions also:

@if not "%~1" == "" for /F "delims=" %%I in ('dir "%~1\*" /AD-L /B /S 2^>nul') do @%SystemRoot%\System32\robocopy.exe "%%I" "%~1" /MOV /NDL /NFL /NJH /NJS /R:1 /W:1 >nul

ROBOCOPY with the used options moves always all files including hidden files and read-only files independent on existing files in destination folder to the folder passed as argument string to the batch file also with just updating the file allocation table of the file system. But please note that the single command line solution using ROBOCOPY as posted here does not work on folder path ending with a backslash like on passing the root directory of a drive like D:\ to the batch file. The backlash at end is in this case interpreted by ROBOCOPY as escape character for " marking end of destination path and ROBOCOPY interprets therefore all options up to /W:1 as part of the destination path. The destination path with " and : would be interpreted as invalid by the file system and so no files are moved in this case. There would be additional code necessary in the batch file to handle also such a use case with passed folder path ending with a backslash on using ROBOCOPY.

2. Shortcut file for file movement

There is necessary next a shortcut file with file extension .lnk in the SendTo folder of the user account.

Such a shortcut file can be created by clicking with secondary pointing device button on the batch file %USERPROFILE%\MoveFilesToFolder.cmd and clicking with primary pointing device button in submenu Send to on the item Desktop (create shortcut).

The user´s desktop has now a shortcut file with name MoveFilesToFolder.cmd.lnk whereby the file extension .lnk is not visible on desktop. There should be first clicked with secondary pointing device button on this shortcut and use from context menu Rename to change the file name, for example, to Move files which is later the name of the menu item in the Send to context submenu.

Then a secondary pointing device button click on the shortcut Move files is needed to open again the context menu and clicking this time on last menu item Properties to open the properties window for the shortcut file.

The property Target should be modified to:

 %SystemRoot%\System32\cmd.exe /D /E:ON /V:OFF /C "%USERPROFILE%\MoveFilesToFolder.cmd"

The property Start in should be cleared whereby the directory specified here does not really matter and could be also kept as is. It defines the current directory on execution of cmd.exe which is not important for the batch file which works independent on which directory is the current directory of cmd.exe processing the batch file. There could be used also %SystemRoot%\System32 for Start in which is the directory containing cmd.exe for an even more fail-safe configuration.

The property Run can be configured with selecting Minimized to run cmd.exe for processing the batch file with a minimized window. Please note that when the minimized window does not disappear, the command MOVE prompts the user for overwriting a file. In this case the window must be restored and the prompt answered. There can be used in the batch file as second line also @pause on using the solution with command MOVE and use Normal window for Run in the shortcut file to always see the results of the file movements.

All other properties can be configured by the user according to personal preferences. The selection of a nice icon would be good and a good comment before clicking on button OK.

The shortcut file is now ready for being cut with Ctrl+X and pasted with Ctrl+V into the folder opened by entering in address bar of Windows File Explorer the string %APPDATA%\Microsoft\Windows\SendTo and hitting RETURN or ENTER on Windows Vista and newer Windows client versions. The SendTo directory is on Windows XP and Windows Server 2003 the directory %USERPROFILE%\SendTo.

3. How to use the shortcut and the batch file?

The user can now click with secondary pointing device button in Windows File Explorer on a folder and click in opened context menu in submenu Send to on the menu item Move files.

explorer.exe calls now the Windows kernel library function CreateProcess to run cmd.exe with all the arguments specified with property Target in the shortcut file with appending to the end the fully qualified name of the clicked folder as additional argument. The property Start in in shortcut file defines the string of which function parameter lpCurrentDirectory points to. Most of the other properties in the shortcut file determine other values passed via the STARTUPINFO structure to function CreateProcess.

A user has a lot of control about how cmd is started for processing a batch file with the usage of a shortcut file which is the reason why I recommend using never directly a batch file on desktop, in Windows Start menu, or in special folders like SendTo or Startup.

It could happen that a user clicks with secondary pointing device button on a file and clicks by mistake on menu item Move files in the context submenu Send to instead of the menu item which should be really clicked. The batch file is designed to do nothing in this case caused by running the batch file by mistake with a fully qualified file name as argument string.

Dynamic abbrev expand for the shell

First to give a definition:

M-xdescribe-functionEnterdabbrev-expandEnter

...
Expands to the most recent, preceding word for which this is a prefix.

Given that bash seems to be most heavily influenced by Emacs, looking there first reveals a few possibilities:

man bash(1), readline section

dynamic-complete-history (M-TAB)
Attempt completion on the text before point, comparing the text
against lines from the history list for possible completion matches.
dabbrev-expand
Attempt menu completion on the text before point, comparing the text
against lines from the history list for possible completion matches.

By default (or my system at least), M-/ is already bound to complete-filename:

$ bind -l | grep /
"\e/": complete-filename

You could re-bind it by putting

"\e/": dabbrev-expand

in your ~/.inputrc or /etc/inputrc.

Note that it only seems to complete the first word (the command), and only from history, not from the current command line as far as I can tell.

In zsh, I can't see anything in the man page that does this, but it should be possible to make it happen by figuring out the appropriate compctl command (Google mirror).

Is it possible to access the launching shortcut directory from a Python executalbe?

When you launch a shortcut, Windows changes the working directory to the directory specified in the shortcut, in the Start in field. At this point, Windows has no memory of where the shortcut was stored.

You could change the Start in field to point to the directory that the shortcut is in. But you'd have to do that for every single shortcut, and never make a mistake.

The better approach is to use a script, rather than a shortcut. Place your actual Python script (which we'll call doit.py for sake of example) somewhere in your PYTHONPATH. Then create a single-line Python script that imports it:

import doit

Save it (but don't name it doit.py) and copy it to each directory from which you want to be able to invoke the main script. In doit.py you can use os.getcwd() to find out what directory you're being invoked from.

You could also do it with a batch file. This is a little more flexible in that you can specify the exact name of the script and which Python interpreter should be used, and don't need to store the script in a directory in PYTHONPATH. Also, you don't need to worry about the file's name clashing with the name of a Python module. Simply put this line in a file:

C:\path\to\your\python.exe C:\path\to\your\script.py

Save it as (e.g.) doit.bat and copy it into the directories from which you want to invoke it. As before, your Python script can call os.getcwd() to get the directory. Or you can write it so your Python script accepts it as the first argument, and write your batch file like:

C:\path\to\your\python.exe C:\path\to\your\script.py %cd%

Another thing you can do with the batch file approach is add a pause command to the end so that the user is asked to press a key after the script runs, giving them the opportunity to read any output generated by the script. You could even make this conditional so that it only happens if an error occurs (which requires returning a proper exit code from the script). I'll leave that as an exercise. :-)

How to change the Jupyter start-up folder

Jupyter Notebook and JupyterLab < 3.0

For old Jupyter Notebook interface installed with notebook package and run as jupyter notebook (see the next section for the identical interface installed with nbclassic and run with jupyter nbclassic, and for JupyterLab):

  1. Open cmd (or Anaconda Prompt) and run jupyter notebook --generate-config.

  2. This writes a file to C:\Users\username\.jupyter\jupyter_notebook_config.py.

  3. Browse to the file location and open it in an Editor

  4. Search for the following line in the file:
    #c.NotebookApp.notebook_dir = ''

  5. Replace by c.NotebookApp.notebook_dir = '/the/path/to/home/folder/'

    Make sure you use forward slashes in your path and use /home/user/ instead of ~/ for your home directory, backslashes could be used if placed in double quotes even if folder name contains spaces as such :
    "D:\yourUserName\Any Folder\More Folders\"

  6. Remove the # at the beginning of the line to allow the line to execute

JupyterLab >= 3, Jupyter Notebook Classic, and RetroLab

For recent nbclassic and JupyterLab >= 3 use c.ServerApp.root_dir instead of c.NotebookApp.notebook_dir (and jupyter server --generate-config instead of jupyter notebook --generate-config).

For context see migration guide and this question on differences between server and notebook.

How can I open a cmd window in a specific location?

Try out this "PowerToy" from Microsoft:

Open Command Window Here

This PowerToy adds an "Open Command
Window Here" context menu option on
file system folders, giving you a
quick way to open a command window
(cmd.exe) pointing at the selected
folder.

EDIT : This software will not work on any version of Windows apart from Windows XP.

Sample Image

What is the point of WORKDIR on Dockerfile?

According to the documentation:

The WORKDIR instruction sets the working directory for any RUN, CMD,
ENTRYPOINT, COPY and ADD instructions that follow it in the
Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

Also, in the Docker best practices it recommends you to use it:

... you should use WORKDIR instead of proliferating instructions like
RUN cd … && do-something, which are hard to read, troubleshoot, and
maintain.

I would suggest to keep it.

I think you can refactor your Dockerfile to something like:

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ "npm", "start" ]


Related Topics



Leave a reply



Submit