Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Asking for admin permissions in Windows using bash script

I’m trying to alter my hosts file in Windows using a bash script.

It looks like this:

echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts

It looks like I need admin permissions, how can I get those? I tried this, but it didn’t work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cd C:\\Windows\\System32\\drivers\\etc

chmod +x hosts

echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts

Result

chmod: changing permissions of 'hosts': Permission denied
bin/exec.sh: line 5: C:\Windows\System32\drivers\etc\hosts: Permission denied

Having to accept a pop-up that asks for permissions is acceptable!

>Solution :

It is unfortunately very complicated to achieve this without external tools.

I recommend this very useful tool: https://github.com/gerardog/gsudo – it works like sudo but for Windows.

Note however that gsudo echo .. >> .. won’t be enough because the >> .. part is done by the shell which is not elevated and gsudo probably can’t run echo since that’s a builtin, but gsudo 'bash -c echo .. >> ..' should work:

gsudo 'bash -c echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts'

Note: If this doesn’t work because either your bash.exe is not in your Windows PATH or because despite this being MINGW bash you also have WSL installed and gsudo would start that instead, then you can always use cmd instead of bash:

gsudo 'cmd /c echo "<ip_address> <replacement>" >> C:\Windows\System32\drivers\etc\hosts'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading