Shell scripts aren't quite the same as typing at a terminal.
What's going to happen here is that iptables-save
is going to wait for sudo su
to complete, and then run. What you want is to run iptables-save
inside the sudo
.
Secondly, sudo su
is among the ranks of 'useless use of' examples. The proper equivalent is
sudo -i
.
There are 2 approaches you can take to solving this.
Method 1
sudo -i <<'EOF'
iptables-save | awk '/^[*]/ { print $1 }
/^:[A-Z]+ [^-]/ { print $1 " ACCEPT" ; }
/COMMIT/ { print $0; }' | iptables-restore
EOF
This basically launches a root shell and sends that command through the shell.
The reason we don't don't just add a sudo
in front of both the iptables-save
and iptables-restore
commands is that it will launch 2 sudo
s at the same time. This does not work well if they both end up trying to prompt for the password.
So this solution works around the issue by only launching a single sudo
.
One line
As requested in your comment, you can do this in a single line, but it becomes much harder to read.
sudo -i sh -c 'iptables-save | awk '\''/^[*]/ { print $1 }; /^:[A-Z]+ [^-]/ { print $1 " ACCEPT" ; }; /COMMIT/ { print $0; }'\'' | iptables-restore'
Method 2
sudo -v
sudo -n iptables-save | awk '/^[*]/ { print $1 }
/^:[A-Z]+ [^-]/ { print $1 " ACCEPT" ; }
/COMMIT/ { print $0; }' | sudo -n iptables-restore
This solution runs sudo
the first time, without any command, simply a -v
. This causes sudo
to prompt for your password if your session is expired. Then any commands run within that session expiration window won't require a password. So launching 2 sudo
s at the same time is no longer an issue as neither of them will prompt (we add -n
to make absolutely sure of this. It'll throw an error if it tries).
sudo
to runsu
! You can usesudo -i
forsudo su -
orsudo -s
forsudo su
sudo -i
andsudo -s
in plain English? I have read the man pages and am still clueless. (I do not have a technical or IT background.) The man pages do not provide examples of instances where one might usesudo -i
oversudo -s
sudo -i
gives you login shell. It means, that shell configuration files, like/etc/profile
are applied - you get shell, similar to the one, when you directly login on given user.sudo -s
don't do this, giving you non-login shell - likesu
- just switch user./etc/default/grub
or/dev/snd
, I must usesudo -i
. Can you provide an example in which I have to usesudo -s
?sudo -s
andsudo -i
. The problem is related to environment variables, like PATH. In some distributions, you couldn't see some commands, because they are in/sbin
dir, and PATH for normal user, doesn't include it. THe same problem is with DISPLAY, when you would like to run GUI command.