1

There are two accounts in my linux computer, appuser and root. For testing purpose I wroto below code into /home/appuser/.profile

export key=value

then as root I execute below commands separately:

1. runuser -l appuser -c "echo key=$key"

   expected: key=value
   result:    key=   

2. runuser -l appuser -c "/home/appuser/test.sh"

    test.py includes only two lines:

    #!/bin/bash
    echo "key=$key"

    expected: key=value
    result:    key=value

Why can't the first command return the correct result?? Is that because .profile is not sourced during execution? why?

Kenster
  • 23,465
  • 21
  • 80
  • 106
Wallace
  • 561
  • 2
  • 21
  • 54
  • Yes, whatever shell you are using is not sourcing your `.profile` which contains the `key` declaration and assignment. – fpmurphy Apr 12 '21 at 01:06

2 Answers2

0

The first thing you did , didn't call "bash"..... and that users profile wasn't read.

When you ran the bash shell script, the first line initiates "bash"..... and from man "bash" :

"When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable."

Dharman
  • 30,962
  • 25
  • 85
  • 135
linuxnut
  • 58
  • 5
0
runuser -l appuser -c "echo key=$key"

Because it's in double quotes, $key is evaluated in the context of the current shell, not the shell you're launching. It's not set in your shell, so the command that is run is effectively:

runuser -l appuser -c 'echo key='

The variable never even makes it to the runuser command.

Use single quotes or escape the dollar sign to prevent interpolation.

runuser -l appuser -c 'echo key=$key'
runuser -l appuser -c "echo key=\$key"

Further reading:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578