0

Im writing simple script, to be run by root, which needs to run some parametrized commands in other users behalf

Eg in below sample I'd like to make dir with version taken from variable 'VER' But whatever I did it doesnt work... VER variable value is not being correctly passed to command (Ive tried surround command by double quotes etc)

VER='10.2.1'
su - other_user -c 'mkdir -p /home/other_user/$VER'

Any idea how to archieve that ?

Maciej
  • 101
  • 6

2 Answers2

3

You pass variables into the command that you execute with su -c in just the same way you pass variables into a sh -c (or bash -c) script:

su other_user -c 'mkdir -p "/home/other_user/$1"' sh "$VER"

The two arguments sh and "$VER" will be passed to the shell that su starts in $0 (used in error messages by that shell) and $1, respectively.

Related:

Kusalananda
  • 333,661
0

Double quotes should achieve it. You'll need to lose the echo of course.

steve@DESKTOP-E197DDI:~$ VER='10.2.1'
steve@DESKTOP-E197DDI:~$ su - steve -c "echo mkdir -p /home/other_user/$VER"
Password:
mkdir -p /home/other_user/10.2.1
steve@DESKTOP-E197DDI:~$
steve
  • 21,892