Reputation: 65
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?
Upvotes: 0
Views: 649
Reputation: 29345
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"
Upvotes: 1
Reputation: 15418
Exactly as you have it seems like it ought to work.
Maybe try a bash call explicitly. That works even if you need a separate input redirection.
$ echo "$pw"|sudo -S bash -c "head -3 < foo"
0
1
2
If you need to pass a file argument, maybe explicitly bind your stdin elsewhere.
$ echo "$pw"|sudo -S bash -c "head -5 foo </dev/null"
0
1
2
Upvotes: 0
Reputation: 6083
Since the sudo
password doesn't need to be repeated for two consecutive sudo
commands, I should issue two sequential commands:
echo "mypass" | sudo -S -v
sudo nvim "filename" # will not prompt for password this time
Explanation: sudo -v
just updates the credentials of sudo
without executing any command.
Upvotes: 0