0

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?

2

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.

2

Ok assuming the bit in grey is your my_script.sh there are a few issues. First, the alias needs to be set in your .bashrc not in the file. More detail is here.

Now onto the script the -r test checks if the file is readable not if it is editable. You probably have read but not write permissions. So you should try

#! /bin/bash

if test -w $1 
then
   /usr/bin/vi $1
else
   sudo /usr/bin/vi $1
fi

This should work. One tip I would add is that if you are having a problem with a bash script: Cover it in echo statements! One at the start to check it opens, one in each side of the the if statement to see where it goes.

  • it is also a nice approach. – souravc Dec 27 '13 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.