首页 > 解决方案 > 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

标签: linuxbashshellmountpi

解决方案


您移动了-o选项而不移动其参数。-o开关和紧随其后的字符串是一个单元。

此外,请尽量mkdir -p避免收到错误消息。但请注意,错误消息表明该命令试图uid=pi,gid=pi用作挂载点;也许mkdir一直以来都是不必要的。

#!/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"

由于这里没有特定于 Bash 的代码,我切换到sh. 我将该-e选项移到脚本中,因此无论您如何运行脚本都无关紧要。

也许以某种方式取出sudo命令会更好,如果用户缺乏权限或无法使用sudo. 那么脚本也适合作为root.


推荐阅读