2

I would like to append some commands to ${HOME}/.bashrc file.

I made a script to do it.

# file name : setup_bash
bashrc_path="${HOME}/.bashrc"
comment="test"
sudo echo "${comment}" >> "${bashrc_path}"

and run it by

bash setup_bash

And it results in an error.

setup_bash: line 19: /home/user/.bashrc: Permission denied

line 19 is at (sudo echo ...).

Next I tried the following code,

sudo bash setup_bash

It results in success.

What is the difference of them? Please teach me it.

mora
  • 2,217
  • 4
  • 22
  • 32

2 Answers2

8

Shell i/o redirection happens before a command executes. That is, when you run...

sudo echo "some text" >> /some/path

...the shell opens /some/path for input before it ever runs the echo command. The implication of this is that the i/o redirection is not going to be affected by the sudo command (because the redirection happens before sudo even runs). On the other hand, when you run...

sudo bash setup_bash

...you are running the entire script as the root user, which means that when it comes time to perform the i/o redirection the script is already running as root and so the redirection will succeed.

larsks
  • 277,717
  • 41
  • 399
  • 399
1

The problem is that in

sudo echo "${comment}" >> "${bashrc_path}"

the shell (STDOUT) redirection (write -- append) operation >> "${bashrc_path}" is done first by the shell, as the user invoking user, this is done even before the main command is executed. And presumably the invoking user has no permission to open the file for writing, hence the permission denied error message from shell; this is irrespective of the command sudo echo ... because that command has not been started executing even by then.

Now when you used sudo at invocation time you are impersonating root (default) so the redirection -- write (append) operation would succeeed, (and as you might have guessed you don't even need the sudo in front of echo now).

heemayl
  • 39,294
  • 7
  • 70
  • 76