#!/bin/csh -f # sudo_if_necessary # ----------------------------------------------------------------------------- # C shell script to try a command and if it fails, retry via sudo. # ----------------------------------------------------------------------------- # Revision History: # $Log$ # ----------------------------------------------------------------------------- set ostype = "`printenv OSTYPE`" if ("$ostype" == "linux") then set os = "linux" else if ("$ostype" == "darwin") then set os = "mac" else echo "Unknown OSTYPE: $ostype. Assuming Linux-compatible..." set os = "linux" endif set p1 = "" set p2 = "" set skip_p2 = "false" if ("$os" == "linux") then if ($#argv >= 2) then set p1 = $1:q set p2 = $2:q shift shift if ("$p1" == "tail" && "$p2" == "-F") then # Translate: tail -F # to: tail --follow=name # Because -F implies not only --follow=name, but also --retry. # Ordinarily that's what you want, so it's a common mistake when # calling this script. But in this case, it prevents the tail # command from ending when a file is not accessible for permission # reasons. So the if statement never executes to decide whether # to try again w/sudo. # No. This didn't work. # Even without --retry, --follow-name still waits forever. # Outputs an error message, but does not end. # Instead, test for accessibility and existence by omitting # the -F option entirely. #set p2 = "--follow=name" set skip_p2 = "true" else if ("$p1" == "tail" && "$p2" == "--follow=name") then set skip_p2 = "true" endif endif else # Do NOT translate tail -F command to tail --follow=name on Mac. # Mac doesn't support --follow or --retry. Only -f and -F. # So tail ends, as desired, with an error code on inaccessible files. endif # Note: Do NOT use $p1:q and $p2:q from here on. # If there were less than 2 args or the OS is not Linux, p1 and p2 are # empty strings, and will be entirely ignored. If we used :q, they'd # become pairs of empty quotes (""), and would lead to the error: # : Command not found. set rc = 0 # Successful so far if ("$skip_p2" == "true") then # Echo the command as though we used p2. Makes more sense to the user. echo "$p1 $p2 $*:q > /dev/null" # Skip p2 which was "-F" on the tail command. Test for accessibility # without it, hiding the output from the user since it's not really # the full command he specified. # Note: Do not redirect stderr. Want the user to see any error, # to understand why we had to use sudo. $p1 $*:q > /dev/null set rc = $status # Still 0 if no error endif # Now that we're past the -F difficulty, try the command without sudo, # and if necessary with sudo. if ("$rc" == "0") then (set echo; $p1 $p2 $*:q) set rc = $status endif if ($rc) then echo "" echo "Using sudo since it failed without sudo..." (set echo; sudo $p1 $p2 $*:q) endif