I want to perform the set of actions inside a different user while running my script, so i am using HEREDOC to perform such actions, but no matter alternatives i try, i cannot able to reference my values in loop inside the HEREDOC.
In this case it prints the first line and exits.
#!/bin/bash
func () {
test=("$@")
sudo su - someuser <<- EOF
echo "${test[*]}"
for i in "${test[@]}" ; do
echo "$i"
done
EOF
}
arrVar=("AC" "TV" "Mobile" "Fridge" "Oven" "Blender")
arrVar+=("hello. why would it fail now with spaces then")
func "$arrVar" ###### Tried this as well "${arrVar[@]}"
prints the output as like this:
[root@ip-10-9-1-1 ~]# ./test.sh
AC
it works fine just fine if i remove the HEREDOC and run as currentUser, but i need to run this as Different User.
EDIT: @roaima answer looks to be promising , but i had to access lot of outside variables, hence passing them as below wouldn't scale well enough for me.
sudo -u someuser bash -c ' ' -- "lot" "of" "variables" "$@"
so i came to this question in the first place using arrays over strings because of the IFS being not respected inside HEREDOC, perhaps i will get better answer if i post my original issue.
so here it it is:
cp="/usr/bin/cp"
rm="/usr/bin/rm"
mv="/usr/bin/mv"
exec_operations () {
echo "Executing operations: $@"
operations=$@
date=$(date +%Y-%m-%d-%H-%M-%S)
sudo su - someuser <<- EOF
IFS=";"
for operation in $operations ; do
echo "Performing the following $operation with $cp, $rm & $mv"
done
unset IFS
EOF
}
text="cp /tmp/text.txt something/;cp /tmp/text2.txt something/;"
exec_operations "$text"
func "${arrVar[@]}"
for operation in "${operations}" ; do