Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shell variables in su command string?

Tags:

bash

sh

su

In Shell script i am trying to pass an array to a Sudo SU command as shown below

VAR=(1,2,3)
sudo su $USER -c "for p in ${VAR[@]} ; do echo $p ; done;"

Issue is $p value is not getting printed. I have tried all the below possible way but not able to print $p value

sudo su $USER -c "for p in "${VAR[@]}" ; do echo "$p" ; done;"
sudo su $USER -c 'for p in ${VAR[@]} ; do echo $p ; done;'

Sample Output of the command

+ sudo su USER -c 'for p in 1 2 3 4 5 ; do echo  ; done;'
+ echo "Script Ended"
like image 632
Dinesh Avatar asked Aug 14 '26 08:08

Dinesh


1 Answers

You could use sh as an argument to sudo su, to pass the variable, then, inside the -c call, you can access the var as you would do in a regular function call ($@ $1 ...);

sudo su $USER -c 'for p in "${@}"; do echo ${p}; done;' sh "${arr[@]}"
so@deb:~$ arr=(1 2 3)
so@deb:~$ sudo su $USER -c 'for p in "${@}"; do echo ${p}; done;' sh "${arr[@]}"
1
2
3
so@deb:~$
like image 142
0stone0 Avatar answered Aug 17 '26 01:08

0stone0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!