I am working on a project, in which I have to connect to Bluetooth low energy device. I am able to connect and do data transfer from command line. But I want to do from script
Here is my script
I think the biggest problem is here is the misconception about what sudo does and what it doesn't:
sudo will run a command as another user (usually as root), but: it is NOT a shell and neither it is a shell replacement!
I wonder why the user account you use to run the script is not allowed to run the commands within the script. If the commands are privileged in nature then use a privileged user which can run them natively. call the whole script via sudo instead of embedding sudo-enabled calls into the script.
If you really need to do it the way you tried use su instead of sudo and use sudo only to call the script:
#! /bin/sh
[...]
su - <user> -c <your command along with options>
[...]
embdesnithin@embdesnithin:~$ sudo sh ble_connect_write.sh
su: invalid option -- 'i'
Usage: su [options] [LOGIN]
Options:
-c, --command COMMAND pass COMMAND to the invoked shell
-h, --help display this help message and exit
-, -l, --login make the shell a login shell
-m, -p,
--preserve-environment do not reset environment variables, and
keep the same shell
-s, --shell SHELL use SHELL instead of the default in passwd
ble_connect_write.sh: 7: ble_connect_write.sh: Syntax error: redirection unexpected
You might have an easier time getting this to work if you create a shell script as root that does what you want. Then set it up in sudo to be so that certain user can run it with sudo, but not edit it.
This is what i said at first. IMHO this would solve all the troubles once and for all.
I suppose this is just a matter of correct quoting:
su - embdesnithin -c "hcitool -i hci0 lecc --random EA:74:48:D5:52:6B"
Note the double quotes around the command, analoguous for the other lines.
You should, btw., not use these long options, i.e. "--command" instead of "-c". This only works with the GNU versions of commands, not with the standard command. This way you unnecessary limit the portability of your script.
"/bin/sh" is on most systems a call to the systems default shell which i used as a stand-in. As you seem to work on a Linux-System this should call a bash .