Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 936  / 1 Year ago, fri, january 27, 2023, 6:51:21

I want to make a shell script to run VI with sudo if I try to edit a file that I don't have write permissions and for that I created an alias



    alias vi=my_script.sh

#!/bin/bash
file=$1

if [ -r $file ]
then
/usr/bin/vi $file
else
sudo /usr/bin/vi $file
fi


However, no matter what, when try to edit, let's say /etc/hosts, I still not being allowed to edit it.



What am I doing wrong?


More From » bash

 Answers
5

I have modified your script to work



#!/bin/bash
file=$1
wown=$(/bin/ls -alF $file | awk '{print $3}')

if [ -r $file ] && [ $wown == $USER ]
then
/usr/bin/vi $file
else
sudo /usr/bin/vi $file
fi


And if you wish to access it directly from anywhere, you can put it in PATH (like ~/bin/) rather than making an alias for it.


[#27799] Friday, January 27, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bewre

Total Points: 164
Total Questions: 108
Total Answers: 106

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
bewre questions
Sun, May 14, 23, 13:27, 1 Year ago
Mon, Aug 2, 21, 03:57, 3 Years ago
Thu, Aug 26, 21, 18:05, 3 Years ago
Sat, Aug 6, 22, 21:41, 2 Years ago
Sat, Jul 24, 21, 22:52, 3 Years ago
;