0

I want to run a command as a different user (the current user is root). Thus, I do

su newuser -c 'mkdir "/tmp/test"'

but I have a problem in passing arguments to it

i="name"
su newuser -c 'mkdir "/tmp/$i"'

or in a script

su newuser -c 'mkdir "/tmp/$1"'
AdminBee
  • 22,803
Googlebot
  • 1,959
  • 3
  • 26
  • 41

1 Answers1

1

The reason for the behavior is that inside single quotes, variable expansion is disabled. Inside double-quotes it is enabled. See e.g. this Q&A for more insight.

So, you can try to change your su call as follows:

i="name"
su newuser -c "mkdir '/tmp/$i'"

Since the argument to su is now in double quotes, the $i will be expanded because the single quotes are (to the interpreting shell that will pass the ultimate result to su) simply "text" and not special anymore.

AdminBee
  • 22,803