Search code examples
bashevalsudo

Bash conditional use of sudo


So I have a bash script that, depending on the version it's working against, may need to run some commands with sudo. I have come up with a couple of options, but I guess I'm looking for additional suggestions. Here is a sample script of what I am doing:

Conditional check for version with each command

#!/usr/bin/bash

# script is run by "user1"

version="$1"
export version

if [[ "$version" -eq "10" ]]
then
  cp /tmp/file.txt /data/application/files/file.txt
elif [[ "$version" -eq "11" ]]
then
  sudo -u user2 cp /tmp/file.txt /data/application/files/file.txt
fi

exit 0

Use eval

#!/usr/bin/bash

# script is run by "user1"

version="$1"
export version
export run_as=""

if [[ "$version" -eq "10" ]]
then
  run_as=""
elif [[ "$version" -eq "11" ]]
then
  run_as="sudo -u user2"
fi

eval "$run_as" cp /tmp/file.txt /data/application/files/file.txt

exit 0

The script will always be run by user1. And no matter the version, some commands need to be run as user1. It's only with the upper version that a subset of commands need to be run as user2.

I like eval because I can check once and just add the variable to the necessary commands. I don't like eval because it seems a bit dangerous and just feels icky. But I haven't thought up with a better solution. Any input?


Solution

  • Everything is fine with the eval approach you have taken, but you don't need to use eval, just remove the quotes around your run_as variable and execute like this:

    $run_as cp /tmp/file.txt /data/application/files/file.txt
    

    Bash will interpolate the value of $run_as and create a string that the interpreter will then attempt to execute.