Search code examples
bashvariablesrootsubshell

Variables inside a bash script subshesll


I am trying to run commands as root and capture the output into a variable. However the variable "loopdev" is returning as empty.

sudo bash << "EOF"
whoami
loopdev=`losetup -f --show "${image}"`
echo "####" $loopdev "####"
EOF

The normal output for this command would be like below

$ image=sdimage.img
$ sudo losetup -f --show "${image}"
/dev/loop0

Solution

  • The solution was to pass in the image variable like this:

    image=rpi_2.img
    sudo image="${image}" bash << 'EOF'
    whoami
    loopdev=`losetup -f --show "${image}"`
    echo "####" $loopdev "####"
    EOF
    

    Output:

    root
    #### /dev/loop0 ####