Search code examples
bashsudo

Bash Echo passing to another script, not working as expected


I created a bash file to write some content into a file, which should be written into another users home directory, with the users account.

It should work the follwing:

sudo ./USER.sh run 49b087ef9cb6753f "echo test > test.txt"

Basically USER.sh contains this:

if [ "$1" = "run" ]; then

  cd /home/${2}/;
  sudo -u ${2} ${3};

fi

But it does not write any stuff into test.txt, it just direct executes the Bash command, instead of writing it into the file.

Did anyone got an Idea how I can fix it, that it does actually write the Content into a file instead of direct executing it?

Thanks.


Solution

  • You want:

    sudo -u "$2" sh -c "$3"
    

    The curlies are useless. They don't prevent splitting and file-globbing. The double quotes do.

    With the double quotes "$3" expands to "echo test > test.txt" (without them, it's "echo" "test" ">" and "test.txt"). This needs to be executed by a shell, hence the sh -c (a POSIX shell is sufficient in this case and if it's dash, it'll start a few ms faster than bash does).

    You could also do:

    if [ "$1" = "run" ]; then
      sudo -u "$2" --set-home sh -c "$(printf '%s\n' 'cd "$HOME"' "$3")"
    fi
    

    which would be more robust in the general case where user home directories aren't necessarily /home/$username, but whatever the appropriate field in /etc/passwd is.