bashsudocmdline-args

how can a single command take stdin in one program and filename in other


What i'm trying to do is pass argument into the second program in such a way that it takes cmdline-args and is opened with sudo but doesn't have anything to with stdin that i pass to sudo.

Below is an example to understand what i'm trying to do.

echo "mypass" | sudo -S nvim "filename"

Here sudo must take stdin and nvim must take a file-name from cmdline-arg. But nvim opens an unnamed file and puts stdin into that file and doesn't even care about the args i pass to it.

My end goal is not to only open file without entering password but to understand how can i pass arguments the way i want to

Is it even possible?


Solution

  • Simply pass the filename as first argument of your script:

    echo "<your password>" | sudo -S nvim "$1"
    

    and call the script with:

    ./script.sh myfile.txt
    

    Note that the -S option of sudo behaves differently depending if the credentials are already cached or not. Better also use the -k option to invalidate the credentials:

    echo "<your password>" | sudo -k -S nvim "$1"