Search code examples
linuxbashshellmountpi

My command works on terminal but doesnt work on script in pi


so I am trying to execute the command: sudo mount /dev/sda1 /mnt/usb -o uid=pi,gid=pi

It works and mounts my USB to the /mnt/usb directory.

so I wanted to create a script thats basicially this:

#!/bin/bash
    sudo mount /dev/sda1 /mnt/usb -o uid=pi,gid=pi
    echo "Script Worked"

and aliased it to "usbmount".

When I call "usbmount" in terminal I get the output of "Script Worked"

but USB doesnt appear to be mounted. I made sure the command works, I looked at the fstab data and it is correct too..

What am I missing? whats the problem?

Edit: When I tried the script with #!/bin/bash -e , it says mount: uid=pi,gid=pi: mount point does not exist.

Edit 2: adding sudo mkdir /media/usb; sudo chown -R pi:pi /media/usb at the start of the script did not work either unfortunately.

Edit 3:* updated script looks like this:

#!/bin/bash -e
    sudo mkdir /mnt/usb; sudo chown -R pi:pi /mnt/usb
    sudo mount -o /dev/sda1 /mnt/usb uid=pi,gid=pi


echo "Script Worked"

and the output I get is:

mkdir: cannot create directory ‘/mnt/usb’: File exists
mount: uid=pi,gid=pi: mount point does not exist.
Script Worked

Solution

  • You moved the -o option without moving its argument. The -o switch and the string immediately after it are a unit.

    Also, try mkdir -p to avoid getting an error message. Notice, though, that the error message suggests that the command tried to use uid=pi,gid=pi as the mount point; perhaps the mkdir was quite unnecessary all along.

    #!/bin/sh
    
    set -e
    
    sudo mkdir -p /mnt/usb
    sudo chown -R pi:pi /mnt/usb
    sudo mount -o uid=pi,gid=pi /dev/sda1 /mnt/usb
    
    echo "Script Worked"
    

    As there is no Bash-specific code here, I switched to sh. I moved the -e option into the script so it doesn't matter how exactly you run the script.

    Perhaps in some way it would be better to take out the sudo commands, and let the script fail if the user lacks the privileges or fails to run the script with sudo. Then the script is also suitable for running as root.